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?
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:
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:
Hope that helps.