JavaScript if 语句总是返回 true

标签 javascript boolean-logic boolean-expression

对应的html:

<html>
<title></title>
<head>

</head>
<body>
<FORM NAME="Calculator">
<TABLE BORDER=4>
<TR>
<TD>
<input type="text"   name="Input" Size="22" value="">
<input type="text" name="notepad" value="">
<br>
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE="button" NAME="one"   VALUE="  1  " class ="digit" >
<INPUT TYPE="button" NAME="two"   VALUE="  2  " class ="digit" >
<INPUT TYPE="button" NAME="three" VALUE="  3  " class ="digit" >
<INPUT TYPE="button" NAME="plus"  VALUE="  +  " class ="operand">
<br>
<INPUT TYPE="button" NAME="four"  VALUE="  4  " class ="digit">
<INPUT TYPE="button" NAME="five"  VALUE="  5  " class ="digit">
<INPUT TYPE="button" NAME="six"   VALUE="  6  " class ="digit">
<INPUT TYPE="button" NAME="minus" VALUE="  -  " class="operand">
<br>
<INPUT TYPE="button" NAME="seven" VALUE="  7  " class ="digit">
<INPUT TYPE="button" NAME="eight" VALUE="  8  " class ="digit">
<INPUT TYPE="button" NAME="nine"  VALUE="  9  " class ="digit">
<INPUT TYPE="button" NAME="times" VALUE="  x  " class ="operand">
<br>
<INPUT TYPE="button" NAME="clear" VALUE="  c  " class ="special">
<INPUT TYPE="button" NAME="zero"  VALUE="  0  " class ="digit">
<INPUT TYPE="button" NAME="Execute"  VALUE="  = " class ="solve">
<INPUT TYPE="button" NAME="div"   VALUE="  /  " class ="operand">
<br>
</TD>
</TR>
</TABLE>
</FORM>

<script type = "text/javascript" src="C:\Users\Quonn\Desktop\QBJS\calculatorjs.js">
</script>
</body>
</html> 

JavaScript:

document.onclick = function(x) {
  var info = x.target;
  if (info.className === "digit" || "operand")
  {
    addDigit();
  }
  else {
    math();
  }
}

function addDigit() {
  alert("x");
}

function math() {
  alert("y");
}

x 是从计算器上的按钮点击传入的。即使 info.className 不是数字/操作数,if 语句也会返回 true。 我需要在 if 语句中更改什么才能使其返回 false?

最佳答案

您没有正确使用 || 运算符。

|| 运算符用于OR 两个值。它出现在两个值之间

从你的例子:

首先它检查您的条件的左侧:

info.className === "数字"

如果 true|| 运算符返回 true(它不计算右侧)。

否则它会评估您条件的右侧:

“操作数”

这将总是评估为,因为字符串“操作数”等于 falsey value .

要解决此问题,您需要在 || 运算符的两边使用正确的表达式:

if (info.className === "digit" || info.className === "operand") {
    alert("Yay");
}

关于JavaScript if 语句总是返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15079983/

相关文章:

javascript - 我如何使用 jQuery 查找元素是否包含特定类?

javascript - 如何从LI中获取H3标签的内容

c - C 是否检查 && 语句中的第二个 bool 语句

c# - bool 表达式,为什么只有两个术语?

javascript - 如何在 Chrome 自动完成时获取输入值

C++ 服务器程序 Print While Loop

java - 使用 Java 确定一个月中天数的最简洁方法(使用 boolean 运算符)

python - 为什么 bool 表达式 "1 in (1, 2, 3) == True"为 False?

javascript - 那个 js 表达式安全吗 : if( ! x || doSomething( x[prop], y[prop] ) === false )

javascript - 循环优化改变方向