It is not sorted because you specified the keys that include the variables in the array. Sorting will only move objects on whole keys. You should see your sorting work if you create your array as follows:
var players = [new Player(), new Player()];
although, of course, it will not be very effective, since you do not have a single account for sorting or a method for identifying them. This will be done:
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 this helps.
source share