计算元素是否出现在两个数组中

时间:2015-01-12 21:38:36

标签: javascript arrays counting

我正在尝试创建一个计数器,每playerScores allPlayers allPlayers[i]出现roundWinners,每个玩家的imJbVrPfGG都会增加{。}}。

目前1仅提升为3,而应为allPlayers = ["iMJbVrPfGG","PjCtgHizDF","iQtZ88qyeX","zhvd8mAdhl"]

阵列

roundWinners = ["iMJbVrPfGG","iMJbVrPfGG","iMJbVrPfGG"]

for (i = 0; i < allPlayers.length; i++) { playersScores[i] = 0; } for (i = 0; i < roundWinners.length; i++) { if(roundWinners[i] == allPlayers[i]){ var index = allPlayers.indexOf(roundWinners[i]) playersScores[index]++; } }

代码:

{{1}}

3 个答案:

答案 0 :(得分:2)

由于每个获胜者可能有多个匹配项,因此您需要一个内部循环:

for (i = 0; i < allPlayers.length; i++) {
    playersScores[i] = 0;
    for (j = 0; j < roundWinners.length; j++) {
        if (roundWinners[j] == allPlayers[i]) playersScores[i]++;
    }
}

结果:[3, 0, 0, 0]

演示:http://jsfiddle.net/3pm0msh6/1/

答案 1 :(得分:1)

您的if语句设置不正确。现在,当您递增圆形索引时,您将增加播放器索引...并将Spot 0与Spot 0,Spot 1与Spot 1进行比较。相反,您只需要查看数组中是否存在该值,并像这样更新分数:

for (i = 0; i < allPlayers.length; i++) {
    playersScores[i] = 0;
}
for (i = 0; i < roundWinners.length; i++) {
    var index = allPlayers.indexOf(roundWinners[i])
    if(index >= 0) {
        playersScores[index]++;
    }
}

请注意,我假设playerScores数组保持与allPlayers数组完全同步。

答案 2 :(得分:0)

你需要两个循环。外部循环将遍历每个玩家,内部循环将搜索并计算所有匹配。例如:

for (i = 0; i < allPlayers.length; i++) {
    playersScores[i] = 0;

    for (var j = 0; j < roundWinners.length; j++) { 
        if(roundWinners[j] == allPlayers[i]){
            playersScores[i]++;
        }
    }
}