gpt4 book ai didi

javascript - 了解 while 循环

转载 作者:行者123 更新时间:2023-12-03 21:18:19 25 4
gpt4 key购买 nike

我是 Javascript 的新手,我正在尝试绕过 while 循环。我了解它们的目的,我想我了解它们的工作原理,但我在使用它们时遇到了麻烦。

我希望 while 值自身重复,直到两个随机数相互匹配。目前,while 循环只运行一次,如果我想让它自己重复,我需要再次运行它。

如何设置此循环,使其自动重复 if 语句,直到 diceRollValue === compGuess?谢谢。

diceRollValue = Math.floor(Math.random()*7);
compGuess = Math.floor(Math.random()*7);
whileValue = true;

while (whileValue) {
if (diceRollValue === compGuess) {
console.log("Computer got it right!")
whileValue = false;
}
else {
console.log("Wrong. Value was "+diceRollValue);
whileValue = false;
}
}

最佳答案

那是因为您只是在 while 之外执行随机数生成器。如果您想要两个新数字,则需要在 while 语句中 执行它们。类似于以下内容:

var diceRollValue = Math.floor(Math.random() * 7),
compGuess = Math.floor(Math.random() * 7),
whileValue = true;
while (whileValue){
if (diceRollValue == compGuess){
console.log('Computer got it right!');
whileValue = false; // exit while
} else {
console.log('Wrong. Value was ' + diceRollValue);
diceRollValue = Math.floor(Math.random() * 7); // Grab new number
//whileValue = true; // no need for this; as long as it's true
// we're still within the while statement
}
}

如果你想重构它,你也可以使用 break 来退出循环(而不是使用变量):

var diceRollValue = Math.floor(Math.random() * 7),
compGuess = Math.floor(Math.random() * 7);
while (true){
if (diceRollValue == compGuess){
// breaking now prevents the code below from executing
// which is why the "success" message can reside outside of the loop.
break;
}
compGuess = Math.floor(Math.random() * 7);
console.log('Wrong. Value was ' + diceRollValue);
}
console.log('Computer got it right!');

关于javascript - 了解 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12946193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com