使用圆括号与和或混淆

布谷鸟

我是Java语言的新手,但在我脑海中,如果我未输入'yes'或'no',则下面的语句应该为false。但是,脚本似乎忽略了这一点,只是根据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等于“是”或“否”。任何不是空字符串的字符串都将求值为,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!");
} 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章