计算元素是否出现在两个数组中
Counting If Element Appears in Both Arrays
我正在尝试创建一个计数器,每当 allPlayers[i]
出现在 roundWinners
中时,allPlayers
中的每个玩家都会递增 playerScores
。
目前 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]++;
}
}
您的 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
数组完全同步。
由于每个获胜者可能有多场比赛,因此您需要一个内部循环:
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]
你需要两个循环。外循环将遍历每个玩家,内循环将搜索并计算所有匹配项。例如:
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]++;
}
}
}
我正在尝试创建一个计数器,每当 allPlayers[i]
出现在 roundWinners
中时,allPlayers
中的每个玩家都会递增 playerScores
。
目前 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]++;
}
}
您的 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
数组完全同步。
由于每个获胜者可能有多场比赛,因此您需要一个内部循环:
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]
你需要两个循环。外循环将遍历每个玩家,内循环将搜索并计算所有匹配项。例如:
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]++;
}
}
}