逻辑AND(&&)和OR(||)运算符 [英] Logical AND (&&) and OR (||) operators

查看:115
本文介绍了逻辑AND(&&)和OR(||)运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

逻辑AND(&& )和OR( || )运营商---谁知道他们可能会欺骗我们这样:)

Logical AND (&&) and OR (||) operators --- who knew they could trick us like this :)

他们对JS的定义(根据解释),如下:

Their definition, for JS (according to this explanation), is the following:


expr1 && expr2 =>如果可以转换为false,则返回expr1;否则,
,返回expr2。因此,当与布尔值一起使用时,&&如果两个操作数都为真,则
返回true;否则,返回false。

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.

expr1 || expr2 =>如果可以转换为true,则返回expr1;否则,
,返回expr2。因此,当与布尔值一起使用时,||如果任一操作数为真,则
返回true;如果两者都为假,则返回
false。

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; if both are false, returns false.

测试它,确实它的工作方式与定义一样,但这里是问题:

Testing it, indeed it works just as the definition, but here's the problem:

false || ""  //returns ""
"" || false  //returns false

所以,显然:

(false || "") ==  ("" || false) // true

但遗憾的是

(false || "") === ("" || false) // false

主要有两个问题:


  1. 这是一个错误,或者为什么JavaScript强迫我们使用 == operator
    在使用&& || 运营商?

  2. 为什么javascript无法将expr1转换为 true 在此表达式
    (|| false)?我的意思是,用
    NOT()运算符预先就不那么简单了?

  1. Is this a bug, or why is JavaScript forcing us to use == operator or to pay attention to the order when using && and || operators?
  2. Why is javascript unable to convert expr1 to true in this expression ("" || 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:


如果可以转换为false,则返回expr1; 否则,返回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

有关truthy / falsy的更多信息

More info on truthy / falsy

这篇关于逻辑AND(&&)和OR(||)运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆