我需要帮助我的游戏得分表。
-1 - 我有4个变量:
var Player1Score= 44;
var Player2Score= 12;
var Player3Score= 45;
var Player4Score= 26;
- 2 - 我制作一个数组:
var MyArray=[Player1Score,Player2Score,Player3Score,Player4Score];
- 3 - 对数组进行排序:
MyArray.Sort();
- 4 - 打印:
---------- ----------高分
45
44
26
12
我的问题是:我如何打印订单中的玩家姓名?
就像这样:
---------- ----------高分
PLAYER 3 45
PLAYER 1 44
PLAYER 4 26
PLAYER 2 12
感谢提前。问候
答案 0 :(得分:1)
这是一个显示http://jsfiddle.net/q2Wkh/1/
的jsfiddle我首先做了你发布的例子,没有任何重复,这只是有点棘手。您需要保留哪些玩家具有特定分数的地图
console.log("\n\n Without duplicates\n\n");
var Player1Score= 44;
var Player2Score= 12;
var Player3Score= 45;
var Player4Score= 26;
var MyArray = [Player1Score,Player2Score,Player3Score,Player4Score];
// Create a map of score to player number
var scoreToPlayerNumber = {};
for (var i=0; i < MyArray.length; i++) {
// Add 1 since player 1 is slot 0
scoreToPlayerNumber[MyArray[i]] = "Player " + (i + 1) ;
}
// You wanna sort backwards
MyArray.sort(function(a,b){return b-a});
for (var i=0; i < MyArray.length; i++) {
console.log (scoreToPlayerNumber[MyArray[i]] + " : " + MyArray[i]);
}
要处理重复的分数,您的地图会跟踪哪个玩家从得分中得到的分数到具有该分数的玩家列表。我还改进了变量名称,这有助于思考问题。
console.log("\n\n With duplicates\n\n");
var scores = [45, 43, 42, 48, 45];
var scoreToPlayerNumber = {};
for (var i=0; i < scores.length; i++) {
var score = scores[i];
if ( !scoreToPlayerNumber[score] ) {
scoreToPlayerNumber[score] = [];
}
scoreToPlayerNumber[score].push("Player " + (i+1) );
}
scores.sort(function(a,b){return b-a});
// Some scores are in the list twice, don't print them twice
var seenScores = {};
for (var i=0; i < scores.length; i++) {
var score = scores[i];
if (!seenScores[score]) {
var scorePlayers = scoreToPlayerNumber[score];
for (var j = 0; j < scorePlayers.length; j++) {
console.log(scorePlayers [j] + " : " + scores[i])
}
}
seenScores[score] = true;
}
最后。您正在使用的结构可以进行改进,以提高灵活性。这是一种更简单的方式,以不同的方式处理它;
var players = [
{name: "Player 1", score: 45},
{name: "Player 2", score: 41},
{name: "Player 3", score: 46},
{name: "Player 4", score: 44},
{name: "Player 5", score: 45},
{name: "Player 6", score: 43},
{name: "Player 7", score: 48}
];
players.sort(function(a,b){ return b.score - a.score});
for (var i=0, player; player = players[i]; i++) {
console.log(player.name + " : " + player.score);
}