谁能向我解释为什么这段代码有时会进入一个无限循环(可能是从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 choicewhile(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 choicewhile(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校验是不同的在外部声明,只需删除参数并使用已定义的全局变量即可:var check = function() {...}...var userChoice = prompt("Choose a number between 1 - 100");check();
10-05 20:33