在javascript中进入无限循环的代码

问题描述 投票:-2回答:1

我的代码进入了无限循环,即使我输入 "是 "或 "是"。

以下是我的代码。

var answer = prompt("Are we there yet?");   
while(answer != "yes" || answer != "yeah" ){
    var answer = prompt("Are we there yet?");    
}    
alert("YAY! We made it!!"); 
javascript infinite-loop
1个回答
1
投票

变化 ||&&.

你在问。如果你的答案不是 "是",或者不是 "是"。如果你的答案是 "是",那么你的答案就不是 "是"。如果你的答案是 "是",你的答案就不是 "是"。这就是为什么你有一个无限循环。

请看 德摩根定律 更多详情。谈判 !(answer == "yes" || answer == "yeah") 的结果也是改变or操作符。

var answer = prompt("Are we there yet?");

while(answer != "yes" && answer != "yeah" ){
    answer = prompt("Are we there yet?");    
}

alert("YAY! We made it!!"); 

0
投票

首先,不要重新定义 answer (除去 var 从循环)。) 其次,思考你的循环有三种可能的情况。

answer = "yes"  ->  (answer != "yes") is false, (answer != "yeah") is true. The loop continues.
answer = "yes"  ->  (answer != "yes") is true, (answer != "yeah") is false. The loop continues.
answer = "anything else"  ->  (answer != "yes") is true, (answer != "yeah") is true. The loop continues.

使用逻辑AND && 操作员应该可以解决您的问题。

var answer = prompt("Are we there yet?");
while (answer != "yes" && answer != "yeah") {
  answer = prompt("Are we there yet?");
}
alert("YAY! We made it!!");
© www.soinside.com 2019 - 2024. All rights reserved.