[英]Logical AND (&&) and OR (||) operators
Logical AND ( &&
) and OR ( ||
) operators --- who knew they could trick us like this :) 逻辑AND(
&&
)和OR( ||
)运算符---谁知道他们可以欺骗我们这样:)
Their definition, for JS (according to this explanation), is the following: 对于JS(根据此解释),他们的定义如下:
expr1 && expr2 => Returns expr1 if it can be converted to false;
expr1 && expr2 =>如果可以转换为false,则返回expr1; otherwise, returns expr2.
否则,返回expr2。 Thus, when used with Boolean values, && returns true if both operands are true;
因此,当与布尔值一起使用时,如果两个操作数都为真,则&&返回true; otherwise, returns false.
否则,返回false。
expr1 ||
expr1 || expr2 => Returns expr1 if it can be converted to true;
expr2 =>如果可以转换为true,则返回expr1; otherwise, returns expr2.
否则,返回expr2。 Thus, when used with Boolean values, ||
因此,当与布尔值一起使用时,|| returns true if either operand is true;
如果任一操作数为true,则返回true; if both are false, returns false.
如果两者都为假,则返回false。
Testing it, indeed it works just as the definition, but here's the problem: 测试它,确实它的工作方式与定义一样,但问题在于:
false || "" //returns ""
"" || false //returns false
So, obviously: 所以,显然:
(false || "") == ("" || false) // true
But, sadly 但是,可悲的是
(false || "") === ("" || false) // false
To the main two questions: 主要有两个问题:
==
operator or to pay attention to the order when using &&
and ||
==
运算符或在使用&&
和||
时注意顺序 operators? true
in this expression ("" || false)
?. true
("" || false)
? I mean, isn't it as simple as prepending ""
with the NOT ( !
) operator? !
)运算符前置""
一样简单? It's just how they work. 这就是他们的工作方式。 It's not a bug:
这不是一个错误:
Returns expr1 if it can be converted to false;
如果可以转换为false,则返回expr1; otherwise, returns expr2
否则,返回expr2
This means you can use "default values", like this: 这意味着您可以使用“默认值”,如下所示:
function someFunc(passedParameter){
var newValue = passedParameter || 1337
}
Or run functions when conditions are met: 或者在满足条件时运行函数:
var myBool = true;
myBool && someFunc(); // someFunc will only be evaluated if `myBool` is truthy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.