[removed] sort objects

后端 未结 4 754
温柔的废话
温柔的废话 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:04

    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
    

提交回复
热议问题