任何人都可以向我解释为什么这段代码有时会进入无限循环(大概来自 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();
最佳答案
“旧代码”的问题在于您在 while
条件中使用“严格相等比较”!==
,除非满足以下条件,否则不会满足该条件:由于提示返回字符串值,因此您将 userChoice 转换为数字。如果您使用 !=
代替,它就会起作用。
“新代码”的问题与闭包有关,在 check
函数内部创建了一个新的局部变量 userChoice
因为您传递了一个参数,这意味着检查内部的 userChoice
与您在外部声明的 userChoice
不同,您只需删除该参数并使用您定义的全局变量即可:
var check = function() {...}
...
var userChoice = prompt("Choose a number between 1 - 100");
check();
关于javascript - 为什么此代码有时会使浏览器崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18677349/