JavaScript 中的逻辑运算符是什么?

javascriptweb developmentfront end technology

JavaScript 支持以下逻辑运算符。假设变量 A 包含 10,变量 B 包含 20,则

Sr.No
运算符和说明
1
&& (逻辑与)
如果两个操作数都非零,则条件为真。
例如: (A && B) 为真。
2
|| (逻辑或)
如果两个操作数中有任意一个非零,则条件为真。
例如: (A || B) 为真。
3
! (逻辑非)
反转其操作数的逻辑状态。如果条件为真,则逻辑非运算符将使其为假。
例如: ! (A && B) 为假。

示例

您可以尝试以下代码来了解如何在 JavaScript 中实现逻辑运算符 −

<html>
   <body>
      <script>
         <!--
            var a = true;
            var b = false;
            var linebreak = "<br />";
            document.write("(a &amp;&amp; b) => ");
            result = (a &amp;&amp; b);
            document.write(result);
            document.write(linebreak);
            document.write("(a || b) => ");
            result = (a || b);
            document.write(result);
            document.write(linebreak);
            document.write("!(a &amp;&amp; b) => ");
            result = (!(a &amp;&amp; b));
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
      <p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

相关文章