Javascript:排序对象

时间:2010-06-01 06:59:55

标签: javascript sorting

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函数永远不会被调用,并且数组未被排序。我不确定我的代码有什么问题?

4 个答案:

答案 0 :(得分:12)

它没有排序,因为你已经指定了数组中的变量所属的键。排序只会在整数值键上移动对象。如果您按照以下步骤创建阵列,您应该看到您的排序工作:

var players = [new Player(), new Player()];
但是,当然,它不会非常有效,因为你既没有得分的分数,也没有识别它们的方法。这样做:

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());

希望有所帮助。

答案 1 :(得分:2)

主要问题在于这一行:

  

Array(players).sort(compare);

Array(something)创建一个以something为元素的数组。

console.log(Array(players)); //[[player1, player2]]

使用数字索引数组,而不是像players['player1']

中那样使用像数组一样的对象

运行以下代码(如果您没有Firebug,请将console.log替换为alert)。

function Player() {
  var score;
  //return this.score - else it returns undefined
  this.getScore = function() { return this.score; } 
  this.setScore = function(sc) { this.score = sc; }
}

function compare(playerA, playerB) {
  console.log("called " + playerA.getScore() + " " + playerB.score);
  //compare method should return 0 if equal, 1 if a > b and -1 if a < b
  return (playerA.getScore() == playerB.getScore()) ? 0 
     : ((playerA.getScore() > playerB.getScore()) ? 1 : -1);
}

var players = [];

players[0] = new Player();
players[1] = new Player();
players[2] = new Player();
players[3] = new Player();
players[0].setScore(9);
players[1].score = 14;
players[2].score = 11;
players[3].score = 10;
players.sort(compare);
console.log(players);//prints sorted array

答案 2 :(得分:0)

这可能是因为你的数组中没有任何“数组值” - 文本索引不被视为数组值,而是作为对象属性(数组是javascript中的“伪装对象”)。您可以向任何对象添加任意数量的属性,但是数组特定的方法(如sort)仅将“实际”数组成员作为其参数(即仅使用数字索引)

var arr = new Array()
arr[0] = 1
arr[1] = 2
arr["textual_index"] = 3
alert(arr.length);

最后一行警告“2”而不是“3”,因为只有两个数字索引值。

答案 3 :(得分:0)

你也可以使用如下:

var a = [];
a.push(obj1);
a.push(obj2);
a.sort(compare);

所以你可以使用push方法而不是整数索引