我无法弄清楚为什么这不起作用。如果我在提示符中输入“No”,则会再次给出相同的提示,这意味着再次执行do循环,因为while语句返回true。但是根据我的逻辑,当给出答案“否”时,while语句应返回false并结束do循环。当(answer!=“Yes”)为真且(answer!=“No”)为false时,“and”运算符不应返回false(true&& false ==假)?我在这里弄错了什么?其他一切都有效。
do {
var answer = prompt("Do you want dinner? Yes or No.");
} while (answer != "Yes" && "No");
if (answer == "Yes") {
alert("Great, there is food in the fridge!"); }
else {
alert("Ok. I will ask again later."); }
答案 0 :(得分:3)
while条件错了。第二部分永远是真的。
试试这个:
while (answer != "Yes" && answer != "No");
答案 1 :(得分:0)
function logAnswer(answer) {
console.log(answer != "Yes" && "No");
}
logAnswer("Wub") --> false && true --> false
logAnswer("Yes") --> false && true --> false
logAnswer("No") --> true && true --> true
&& "No"
将评估字符串"否"像真的一样。应该对answer
进行两次评估。我个人认为OR操作符可能在这里读得更好。
while (!(answer == "Yes" || answer == "No")) // OR operator
while (answer != "Yes" && answer != "No") // AND operator
答案 2 :(得分:0)
您的条件表格错误。
do {
var answer = prompt("Do you want dinner? Yes or No.");
} while (answer != "Yes" && answer != "No");
if (answer == "Yes") {
alert("Great, there is food in the fridge!"); }
else {
alert("Ok. I will ask again later."); }
答案 3 :(得分:-2)
您必须在&&
的两边写一个完整的测试。 "No"
将始终评估为true
。
while (answer != "Yes" && answer != "No")