计数时间值#出现在For循环中的数组[Javascript]

时间:2014-12-22 20:04:11

标签: javascript arrays math

所需

在课程游戏中,有一个名为RoundWinners的列,其中包含填充多个UserId的数组。对于玩家获胜的每个 Round ,他们的UserId被添加到数组中:

前端显示一个列表,显示数据库中的每个游戏。对于每个游戏,我想计算当前用户currentUserId赢得的轮数,并将此数字显示为userScore

示例:

当前用户: Bob

游戏1,得分= 2:

[“Bob”,“Sue”,“Joe”,“Bob”]

游戏2,得分= 1:

[“Bob”,“Lahkim”]

游戏3,得分= 0:

[“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,虽然当前用户没有赢得任何回合,并且所有后续游戏都显示“未定义”。

2 个答案:

答案 0 :(得分:1)

你必须为此使用2 for循环...

&#13;
&#13;
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;
&#13;
&#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;