在课程游戏中,有一个名为RoundWinners
的列,其中包含填充多个UserId
的数组。对于玩家获胜的每个 Round ,他们的UserId
被添加到数组中:
前端显示一个列表,显示数据库中的每个游戏。对于每个游戏,我想计算当前用户currentUserId
赢得的轮数,并将此数字显示为userScore
。
当前用户: Bob
[“Bob”,“Sue”,“Joe”,“Bob”]
[“Bob”,“Lahkim”]
[“John”,“Mark”,“Ronnie”,“Alice”]
var userScore = 0;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
if (roundWinners[i] == currentUserId) {
userScore++;
userScores.push(userScore);
};
};
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='GameContainer'> + userScores[i] + </div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;
第一个游戏显示userScore
为1,虽然当前用户没有赢得任何回合,并且所有后续游戏都显示“未定义”。
答案 0 :(得分:1)
你必须为此使用2 for循环...
var roundWinners = [["Bob", "Sue", "Joe", "Bob"],["Bob", "Lahkim"],["John", "Mark", "Ronnie", "Alice"]];
var gameIds = [1,2,3];
var currentUserId = "Bob";
var userScore;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
userScore = 0;
for (j=0; j < roundWinners[i].length; j++){
if (roundWinners[i][j] == currentUserId) {
userScore++;
}
}
userScores.push(userScore);
}
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='BottomContainer'>" + userScores[i] + "</div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;
&#13;
<div id="games"></div>
&#13;
答案 1 :(得分:1)
您持续获得1作为userScore的原因是因为您每次找到匹配项时都会将userScore推送到userScore。相反,您应该循环遍历所有roundWinners,计算currentUserId出现的次数,然后推送到userScores数组。我已在下面编辑了您的代码,并附有表明更改的注释。
var userScore = 0;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
if (roundWinners[i] == currentUserId) {
userScore++;
};
};
//Push to userScores AFTER you finish going through all of the round winners
userScores.push(userScore);
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='GameContainer'> + userScores[i] + </div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;