Javascript:查找具有最高和第二高值的变量

时间:2014-02-25 14:54:06

标签: javascript loops

我想制作一个循环来找到最高和第二高的玩家。我无法在任何地方找到指示。

我有以下变量: Player1 = 25 Player2 = 50 Player3 = 14

我想在变量中保存最高和第二高的玩家。 var highest = highestplayer; var secondhighest = secondhigest;

2 个答案:

答案 0 :(得分:1)

您可以将玩家放入数组并对数组进行排序:

players = [Player1, Player2, Player3];
players.sort(function(x, y) { return y - x; });

var highest = players[0];
var secondhighest = players[1];

如果你想要玩家和积分,你应该考虑使用对象:

Player1 = { name: 'Player1', points: 25 };
Player2 = { name: 'Player2', points: 50 };
Player3 = { name: 'Player3', points: 14 };

players = [Player1, Player2, Player3];
players.sort(function(x, y) { return y.points - x.points; });

var highest = players[0];
var secondhighest = players[1];

alert(highest.name + ': ' + highest.points);
alert(secondhighest.name + ': ' + secondhighest.points);

答案 1 :(得分:1)

首先,玩家需要的不仅仅是存储的整数,所以你可以分辨哪个是哪个。然后他们需要在一个数组中。

var player1 = {name:"Player 1",score:"25"};
var player2 = {name:"Player 2",score:"50"};
var player3 = {name:"Player 3",score:"14"};
var players = [player1,player2,player3];

然后你可以快速循环并拉出最高和第二。

var highestplayer, secondhighest;
for (var i=players.length;i--;) { //quickly walks backwards through an array
  //if highest isn't set yet, or new player beats highest 
  if (!highestplayer || players[i].score > highestplayer.score) {
    //move highest down the ranks
    secondhighest = highestplayer;
    //set the new leader
    highestsplayer = players[i];

  }
  //if second not set or new player beats second
  else if (!secondhigest || player[i].score > secondhighest.score) {
    secondhighest = player[i];
  }
}

但是,如果您想要完整排名,则需要使用排序功能

players.sort(function(a,b) { return b.score-a.score });