[英]Javascript: Find variable with highest and second highest value
I want to make a loop to find highest and second highest player. 我想循环寻找最高和第二高的球员。 I can not find instructions anywhere. 我在任何地方都找不到说明。
I have following variables: Player1 = 25
Player2 = 50
Player3 = 14
我有以下变量: Player2 = 50
Player1 = 25
Player2 = 50
Player3 = 14
I want to save the highest and second highest player in variable. 我想在变量中保存最高和第二高的玩家。 var highest = highestplayer;
var secondhighest = secondhigest;
You can put the players in an array and sort the array: 您可以将播放器放在一个数组中并对数组进行排序:
players = [Player1, Player2, Player3];
players.sort(function(x, y) { return y - x; });
var highest = players[0];
var secondhighest = players[1];
If you want the player and the points, you should consider using objects: 如果需要玩家和积分,则应考虑使用以下对象:
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);
First, players need to more than just a stored integer, so you can tell which is which. 首先,玩家需要的不仅仅是存储的整数,所以您可以分辨出哪个是哪个。 Then they need to be in an array. 然后它们需要放在一个数组中。
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];
then you can quickly loop through and pull out the highest and second. 那么您可以快速循环浏览并拉出最高的和第二个。
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];
}
}
However, if you want to a full ranking, you'll need to use a sort function 但是,如果要获得完整排名,则需要使用排序功能
players.sort(function(a,b) { return b.score-a.score });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.