简体   繁体   English

逻辑AND(&&)和OR(||)运算符

[英]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: 主要有两个问题:

  1. Is this a bug, or why is JavaScript forcing us to use == operator or to pay attention to the order when using && and || 这是一个错误,或者为什么JavaScript强制我们使用==运算符在使用&&||时注意顺序 operators? 运营商?
  2. Why is javascript unable to convert expr1 to true in this expression ("" || false) ?. 为什么javascript无法在此表达式中将expr1转换为true ("" || false) I mean, isn't it as simple as prepending "" with the NOT ( ! ) operator? 我的意思是,是不是像使用NOT( ! )运算符前置""一样简单?

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

More info on truthy / falsy 有关truthy / falsy的更多信息

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

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