[removed] sort objects

后端 未结 4 714
温柔的废话
温柔的废话 2021-01-13 22:46
function Player() {
  var score;

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

function compare(playerA, playerB)         


        
4条回答
  •  生来不讨喜
    2021-01-13 23:01

    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.

提交回复
热议问题