最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sorting - Javascript: sort objects - Stack Overflow

programmeradmin11浏览0评论
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);

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?

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

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?

Share Improve this question edited Jun 1, 2010 at 7:01 Kobi 138k41 gold badges256 silver badges297 bronze badges asked Jun 1, 2010 at 6:59 tomtom 6201 gold badge7 silver badges16 bronze badges 2
  • the fact that it's 'similar' doesn't make it equivalent. There may be nothing wrong with the shown code fragment, but the difference may cause a problem. – xtofl Commented Jun 1, 2010 at 7:08
  • This works only case of score value is integer!. You can do string compare and return -1,0 or 1 as well in compare method – pramodc84 Commented Jun 1, 2010 at 7:13
Add a comment  | 

4 Answers 4

Reset to default 12

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

Hope that helps.

The main problem lies in this line:

Array(players).sort(compare);

Array(something) makes an array with something as its element.

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

Use numeric indexed array instead of using object like array as in players['player1']

Run the following code (replace console.log with alert if you don't have Firebug).

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

It's probably because you don't have any "array values" inside your array - textual indexes are not regarded as array values but as object propertiest (arrays are "objects in disguise" in javascript). You can add as many properties to any object but array specific methods like sort take only "real" array members as their parameteres (i.e. only with numerical indexes)

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

The last line alerts "2" not "3" since there are only two values with numeric indexes.

you can also use like below:

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

so you can use push method rather than an integer index

发布评论

评论列表(0)

  1. 暂无评论