简体   繁体   English

JavaScript逻辑运算符内部

[英]JavaScript logical operators internals

While reading the JavaScript documentation I came across a section that confused me: 在阅读JavaScript文档时,我遇到了一个让我感到困惑的部分

"Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table. “逻辑运算符通常与布尔(逻辑)值一起使用;当它们使用时,它们将返回布尔值。但是,&&和||运算符实际上返回指定操作数之一的值,因此,如果这些运算符与non -布尔值,它们可以返回非布尔值,逻辑运算符如下表所示。

&& Operator: expr1 && expr2

(Logical AND) Returns expr1 if it can be converted to false; (逻辑与)如果可以将其转换为false,则返回expr1;否则返回false。 otherwise, returns expr2. 否则,返回expr2。 Thus, when used with Boolean values, && returns true if both operands are true; 因此,当与布尔值一起使用时,&&如果两个操作数都为true,则返回true;否则为false。 otherwise, returns false. 否则,返回false。

|| Operator: expr1 || expr2

(Logical OR) Returns expr1 if it can be converted to true; (逻辑或)如果可以将其转换为true,则返回expr1;否则,返回false。 otherwise, returns expr2. 否则,返回expr2。 Thus, when used with Boolean values, || 因此,当与布尔值一起使用时,|| returns true if either operand is true; 如果任一操作数为true,则返回true;否则为false。 if both are false, returns false." 如果两者均为假,则返回false。”

Let's say you have: 假设您有:

var a3 = false && true; 

so taking into the consideration the rule for the "and" operator, the variable a3 should contain the value true since "false" cannot be converted to false. 因此,考虑到“ and”运算符的规则,变量“ a3”应包含值true,因为“ false”不能转换为false。

The choice of words "can be converted to false" stems from JavaScript having truthy and falsey values. 单词“可以转换为假”的选择源于具有truefalse值的JavaScript。

All values can be converted to a truthy or falsey value. 所有的值可以被转换为一个或truthyfalsey。

false is falsey, so no type conversion as such would take place, but other values would convert to false, such as: false是falsey,因此不会进行任何类型转换 ,但是其他值将转换为false,例如:

undefined, null, NaN, 0, ""

So the and statement would return false and not true , because false is already false and no conversion would be necessary. 因此,and语句将返回false而不是true ,因为false已经是false并且不需要转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM