在不使用或要求这些变量是全局变量的情况下,没有简单的方法可以遍历变量名,例如player1
,等,这通常是一种不好的方法。player2
eval()
如果它们是全局变量,你可以使用这个技巧,但我建议我在下面使用我的第二种方法,将玩家信息存储为对象数组。这是使用全局变量的技巧(不推荐,但更直接地回答了您的问题):
// these must be global variables
var score1 = 100;
var score2= 99;
var score3= 80;
function findHighScore() {
var highestScore = score1;
var highestScorePlayerNum = 1;
var tempScore;
for var (i = 2; i <= 3; i++) {
// this works only because the score variables are global variables which
// can be accessed as properties off the window object
tempScore = window["score" + i];
if (tempScore > highestScore) {
highestScore = tempScore;
highestScorePlayerNum = i;
}
}
return {score: highestScore, playerNum: highestScorePlayerNum};
}
更好的方法是不将每个玩家的分数保存在自己的 javascript 变量中,而是将其放入如下对象数组中:
var playerData = [
{name: "John", highScore: 145, lastPlayed: 23089234},
[name: "Bill", highScore: 99, lastPlayed: 59383945}
];
然后,您可以遍历玩家数据,找到最高分并获得该玩家的姓名。
function findHighScore() {
var highScoreSoFar = 0;
var result;
for (var i = 0; i < playerData.length; i++) {
if (playerData[i].highScore > highScoreSoFar) {
result = playerDatra[i];
highScoreSoFar = playerData[i].highScore;
}
}
return result;
}
var highPlayer = findHighScore();
alert("Highest scoring player is " + highPlayer.name + " with a score of " + highPlayer.highScore);
如果要返回所有得分最高的玩家,可以返回得分最高的玩家数组:
function findHighScore() {
var highScoreSoFar = 0;
var result = [];
for (var i = 0; i < playerData.length; i++) {
if (playerData[i].highScore > highScoreSoFar) {
// new high score so start a new array with this player in it
result = [playerData[i]];
highScoreSoFar = playerData[i].highScore;
} else if (playerData[i].highScore === highScoreSoFar) {
// more than one player with this highScore so add this one to the array
result.push(playerData[i]);
}
}
return result;
}