我正在尝试用JS编写快照游戏。当卡相同时,控制台将记录“ SNAP!”。好的,但是不会停止。我要加休息时间吗?在错误的地方?
for (mattCounter = 0; mattCounter < mattDeck.length; mattCounter++) {
for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++) {
if (mattDeck[mattCounter] === jamesDeck[jamesCounter]) {
console.log('SNAP!');
break;
} else {
console.log('Go again...');
}
}
};
答案 0 :(得分:0)
该中断只会停止第二个,这意味着:
for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++)
最好的选择是设置一个标志,最初是false,然后除了使循环中断外,还要将其设置为true。 然后,如果该标志设置为true,则也将第一个中断。
var flag = false;
for (mattCounter = 0; mattCounter < mattDeck.length; mattCounter++) {
for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++) {
if (mattDeck[mattCounter] === jamesDeck[jamesCounter]) {
console.log('SNAP!');
flag = true;
break;
} else {
console.log('Go again...');
}
}
if (flag) {
break;
}
};