Javascript 理解while循环
我对Javascript还不熟悉,我正试图在循环时绞尽脑汁。我理解他们的目的,我想我也理解他们是如何工作的,但我在他们身上遇到了麻烦 我希望while值重复自身,直到两个随机数相互匹配。目前,while循环只运行一次,如果希望它自身重复,我需要再次运行它 如何设置此循环,使其自动重复if语句,直到diceRollValue===compGuess?谢谢Javascript 理解while循环,javascript,Javascript,我对Javascript还不熟悉,我正试图在循环时绞尽脑汁。我理解他们的目的,我想我也理解他们是如何工作的,但我在他们身上遇到了麻烦 我希望while值重复自身,直到两个随机数相互匹配。目前,while循环只运行一次,如果希望它自身重复,我需要再次运行它 如何设置此循环,使其自动重复if语句,直到diceRollValue===compGuess?谢谢 diceRollValue = Math.floor(Math.random()*7); compGuess = Math.floor(Math
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
退出循环(而不是使用变量):
您有两个问题,第一个问题是在if和else块中设置
whileValue
,这样无论随机数的值是多少,循环都会在一次迭代后中断
其次,在循环之前生成猜测,以便反复检查相同的值
因此,删除else块中的
whileValue
赋值,并将compGuess
赋值移动到while循环中。将两个随机变量放入循环中
whileValue = true;
while (whileValue) {
diceRollValue = Math.floor(Math.random()*7);
compGuess = Math.floor(Math.random()*7);
if (diceRollValue === compGuess) {
console.log("Computer got it right!")
whileValue = false;
}
else {
console.log("Wrong. Value was "+diceRollValue);
}
}
看起来你给了自己一个复制粘贴错误。复制代码,粘贴代码,但从未更改。但这只是问题的一半
whileValue = true;
while (whileValue) {
diceRollValue = Math.floor(Math.random()*7);
compGuess = Math.floor(Math.random()*7);
if (diceRollValue === compGuess) {
console.log("Computer got it right!")
whileValue = false;
}
else {
console.log("Wrong. Value was "+diceRollValue);
}
}