逻辑运算符(AND运算符) [英] Logical Operators (AND Operators)

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

问题描述

我遇到了以下逻辑运算符解决方法,但无法理解其背后的逻辑:

I came across the following logical operators workaround but could not comprehend the logic behind:

console.log(1 && 2)将使您成为2

console.log(false && X)将使您成为false

console.log(true && X)将使您UncaughtReferenceError:X is not defined

任何人都可以解释答案吗?

Anyone can explain the answer?

推荐答案

查看

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

&&; 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.

在第一个示例中,提供数字1和2作为操作数. 1无法转换为false,因此返回恰好是2的第二个操作数.

In the first example, you provide the numbers 1 and 2 as the operands. 1 cannot be converted to false, therefore the second operand, which happens to be 2, is returned.

最后两个示例非常简单,因为涉及布尔值.如果任一操作数为false,则返回false.仅第三个操作会给您一个错误的原因是,在第二个操作中,第二个操作数(X)不会由于短路而被检查.短路意味着一旦JS看到第一个值是false,它甚至都不会检查另一个值. JS将false视为第一个操作数,并立即返回.

The two last examples are fairly straightforward, as booleans are involved. If either operand is false, you get back false. The reason only the third one gives you an error is because in the second, the second operand (X) is never checked due to short-circuiting. Short-circuiting means that once JS sees that the first value is false, it does not even bother to check the other value. JS sees false as the first operand and immediately returns.

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

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