javascript - 使用带有 and or 的括号会造成混淆

标签 javascript

我是 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/

相关文章:

javascript - href 和 ng-click 在移动设备上的同一个标签中不起作用

javascript - 按钮 onclick 中的值不会增加

javascript - sql - 如何保存客户购买的产品并将其显示在 HTML 表格上

javascript - 使用 Promise 返回多个查询

javascript - jQuery Highcharts 不适用于 JSF 2.0

javascript - 从 location.host 获取根域

javascript - TypeScript 中带有配置对象的构造函数(如 jQuery.extend、Ext.apply)

javascript - 使用 Enter 触发 .click 函数

javascript - 无法摆脱这种类型的错误

javascript - 改变html中的滚动条