我正在经历奥丁项目。有一项作业要求我创建一个石头、剪刀、布游戏。我现在遇到的问题是知道何时结束游戏。
while (computerScore < 3 || playerScore < 3) {
let answer = prompt('Rock, Paper, or Scissors');
console.log(playRound(answer, computerPlay()));
console.log("Computer has " + computerScore + " points and you have " + playerScore + " points.")
}
如果你看上面的内容,你会发现我有一个循环,如果计算机或玩家的分数小于 3,它就会一直循环,但只有当两个玩家都达到 3 时,循环才会停止。我希望循环在以下情况停止:计算机或玩家已达到 3 分。
playRound 是一个函数,用于检查谁获胜并为获胜者分数添加 1 分。
感谢任何帮助!
最佳答案
为了扩展一些告诉您如何修复它的答案,我想指出为什么您的代码不起作用。
目前,您的代码指出,如果玩家的分数小于 3 或计算机的分数小于 3,则执行 while 循环。请记住,只要条件计算结果为 true
,while 条件就会执行循环。
因此,如果计算机的得分为 3,而玩家的得分为 2,则您的条件当前将评估为 true,因为玩家的得分确实小于 3。
您需要使用 &&
运算符,以便当其中一名玩家的分数达到 3 时,您的条件计算结果为 false。
let computerScore = 3;
let playerScore = 2;
//computerScore < 3 = false;
//playerScore < 3 = true;
//while(false || true) evaluates to true
while(computerScore < 3 || playerScore < 3){
//code will always run as long as one of the players' scores is < 3
}
//while(false && true) evaluates to false
while(computerScore < 3 && playerScore < 3){
//code will stop running when either player's score reaches 3
}
关于javascript - 使用 || 进行具有 2 个条件的 While 循环在 JavaScript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54467586/