本文介绍了Javascript:对对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function Player() {
  var score;

  this.getScore = function() { return score; }
  this.setScore = function(sc) { score = sc; }
}

function compare(playerA, playerB) {
  return playerA.getScore() - playerB.getScore();
}

var players = [];

players['player1'] = new Player();
players['player2'] = new Player();

Array(players).sort(compare);

我有与上面相似的代码.当我使用调试器单步执行代码时,compare函数将永远不会被调用,并且数组也不会被排序.我不确定我的代码有什么问题吗?

I have code that is similar to the above. When I step through the code with a debugger, the compare function never gets called and the array isn't sorted. I'm not sure what's wrong with my code?

推荐答案

之所以没有排序,是因为您指定了数组中变量所属的键.排序只会将对象移动到整数键上.如果您按照以下方式创建数组,则应该会看到排序工作:

It's not sorting because you have specified the keys that the variables within the array belong on. Sorting will only move the objects on integer-valued keys. You should see your sorting work if you create your array as follow:

var players = [new Player(), new Player()];

当然,由于您既没有评分依据,也没有识别方法,因此效果不是很好.会做到的:

though, of course, it won't be very effective since you have neither a score on which to sort or a method of identifying them. This'll do it:

function Player(name, score) {
  this.getName = function() { return name; }
  this.getScore = function() { return score; }
  this.setScore = function(sc) { score = sc; }
}

function comparePlayers(playerA, playerB) {
  return playerA.getScore() - playerB.getScore();
}

var playerA = new Player('Paul', 10);
var playerB = new Player('Lucas', 5);
var playerC = new Player('William', 7);

var players = [playerA, playerB, playerC];

for (var i = 0; i < players.length; i++)
    alert(players[i].getName() + ' - ' + players[i].getScore());

players.sort(comparePlayers);

for (var i = 0; i < players.length; i++)
    alert(players[i].getName() + ' - ' + players[i].getScore());

希望有帮助.

这篇关于Javascript:对对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:37