我是 Javascript 新手,但在我看来,如果我不输入"is"或“否”,下面的语句应该是错误的。然而,脚本似乎忽略了这一点,只是根据 a=1 是否返回 true 或 false。有人可以解释我做错了什么吗?非常感谢。
var a = 1;
var box1 = prompt("Type 'yes' or 'no' for statement to be true");
if ((box1 === "yes" || "no") && a === 1) {
alert("Hooray!");
}
最佳答案
您需要将您的条件更改为:
(box1 === "yes" || box1 === "no")
您的条件是评估:box1
等于"is"或“否”。任何非空字符串的字符串都会计算为 true
,因此“no”会转换为 true
,这意味着您的条件始终计算为 true。
var a = 1;
var box1 = prompt("Type 'yes' or 'no' for statement to be true");
if ((box1 === "yes" || box1 === "no") && a === 1) {
alert("Hooray!");
}
关于javascript - 使用带有 and or 的括号会造成混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39431539/