JS:逻辑操作符“||”、“&&”和“!”。
| Operator | Usage | Description |
| - | - |
| Logical AND (&&) | expr1 && expr2 | Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false. |
| Logical OR (||) | expr1 || expr2 | Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true. |
|Logical NOT (!) | !expr | Returns false if its single operand can be converted to true; otherwise, returns true. |
翻译一下:
| 操作符 | 用法 | 描述 |
| - | - |
| 逻辑和 (&&) | expr1 && expr2 | 如果expr1可以被转换为false,那么返回expr1,否则,返回expr2。 如果使用的是布尔值,那么仅当两个操作数都为真时,返回true;否则,返回false。 |
| 逻辑或 (||) | expr1 || expr2 | 如果expr1可以被转换为true,返回expr1;否则,返回expr2。如果是布尔值,则两个操作数中有一个位true就返回true。|
| 逻辑非 (!) | !expr | 如果这个操作数可以转换为true,返回false,否则,返回true |
以下这些表达式都可以转换为false:
- null;
- NaN;
- 0;
- empty string (“” or ‘’);
- undefined.
需要注意的是:操作符有一个优先级的规定,可以参考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence。
参考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators。