谁能向我解释为什么这段代码有时会进入无限循环(可能来自 while 循环)并使浏览器窗口崩溃?是不是有什么关系while(userChoice != randNumber)
,这没有一个足够的结局吗?
var check = function(userChoice) {
while ((isNaN(userChoice)) || (userChoice > 100) || (userChoice < 1) || (userChoice %1 !== 0)) {
userChoice = prompt("Choose a number between 1 - 100", "It must be a whole number!");
}
};
var randNumber = Math.floor(Math.random() * 100 + 1);
var userChoice = prompt("Choose a number between 1 - 100");
console.log(userChoice);
check(userChoice);
//Above sorts out the computer choice and sets the rules for the user choice
while(userChoice != randNumber) {
if (userChoice > randNumber) {
userChoice = prompt("Your number is GREATER than the computer.", "Please re-choose a number between 1 - 100");
check(userChoice);
}
else if (userChoice < randNumber) {
userChoice = prompt("Your number is SMALLER than the computer.", "Please re-choose a number between 1 - 100");
check(userChoice);
}
}
console.log("Your number matches! Congratulations!");
这是对我之前的一些代码的修改,它会更频繁地崩溃。虽然上面的代码更稳定,但它仍然偶尔会崩溃,虽然我无法解释启动无限循环的确切过程。
旧代码如下:( 有人可以优先告诉我为什么会崩溃吗?我不明白为什么当达到正确的数字时while循环没有结束!)
main = function() {
var randNumber = Math.floor(Math.random() * 100 + 1);
var userChoice = prompt("Choose a number between 1 - 100");
while ((isNaN(userChoice)) || (userChoice > 100) || (userChoice < 1) || (userChoice %1 !== 0)) {
userChoice = prompt("Choose a number between 1 - 100", "It must be a whole number!");
}
//Above sorts out the computer choice and sets the rules for the user choice
while(userChoice !== randNumber) {
if (userChoice > randNumber) {
userChoice = prompt("Your number is GREATER than the computer.", "Please re-choose a number between 1 - 100");
}
else if (userChoice < randNumber) {
userChoice = prompt("Your number is SMALLER than the computer.", "Please re-choose a number between 1 - 100");
}
}
return("Your number matches! Congratulations!");
};
main();