2012-10-18 85 views
2

我是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; 
    } 
} 
+0

看起来你给自己一个复制粘贴错误。复制的代码,你粘贴它,并从未改变它。但这只是问题的一半。 :) – epascarello

回答

6

这是因为你只在这段时间之外执行随机数生成器。如果你想要两个新的数字,他们需要在内执行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!'); 
1

你有两个问题,首先是你在if和else块中都设置了whileValue,所以无论随机数的值如何,循环在一次迭代后都会中断。

其次,你在循环之前产生猜测,所以你会一遍又一遍地检查相同的值。

因此,删除else块中的whileValue赋值,并将compGuess赋值移入while循环。

1

将2个随机变量放入循环中。

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); 
    } 
}