Javascript 中的 && 运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8720645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:21:20  来源:igfitidea点击:

&& operator in Javascript

javascriptoperators

提问by Zar

While looking through some code (javascript), I found this piece of code:

在查看一些代码(javascript)时,我发现了这段代码:

<script>window.Bootloader && Bootloader.done(["pQ27\/"]);</script>

What I don't understand is what the &&is doing there, the code is from Facebook and is obviously minified and/or obfuscated, but it still does the same thing.

我不明白的是那里在&&做什么,代码来自 Facebook,显然被缩小和/或混淆,但它仍然做同样的事情。

tl;dr: What does the &&operator do here?

tl;dr:&&操作员在这里做什么?

回答by Sam Dolan

&&makes sure that the Bootloaderfunction/object exists before calling the donemethod on it. The code takes advantage of boolean short circuiting to ensure the first expression evaluates to true before executing the second. See the short-circuit evaluation wikipediaentry for a more in-depth explanation.

&&Bootloader在调用done方法之前确保函数/对象存在。该代码利用布尔短路来确保第一个表达式在执行第二个之前评估为真。有关更深入的解释,请参阅短路评估维基百科条目。

回答by ijse

window.Bootloader && Bootloader.done(["pQ27\/"]);

it is equivalent to:

它相当于:

if(window.Bootloader) {
  Bootloader.done(["pQ27\/"]);
}

回答by Jeff B

&&is an ANDoperator, just like most everywhere else. There is really nothing fancy about it.

&&是一个AND运算符,就像大多数其他地方一样。真的没有什么特别的。

Most languages, JavaScript included, will stop evaluating an ANDoperator if the first operand is false.

AND如果第一个操作数为假,大多数语言(包括 JavaScript)将停止评估运算符。

In this case, if window.Bootloaderdoes not exist, it will be undef, which evaluates to false, so JavaScript will skip the second part.

在这种情况下,如果window.Bootloader不存在,它将是 undef,其计算结果为 false,因此 JavaScript 将跳过第二部分。

If it is true, it continues and calls Bootloader.done(...).

如果为真,则继续并调用Bootloader.done(...)

Think of it as a shortcut for if(window.Bootloader) { Bootloader.done(...) }

把它想象成一条捷径 if(window.Bootloader) { Bootloader.done(...) }

回答by wael

also && operator returns the first encountered value of this kind: null, undefined, 0, false, NaN, ""

&& 运算符还返回第一个遇到的此类值:null、undefined、0、false、NaN、“”

ex: if

例如:如果

var1 = 33
var2 = 0 
var3 = 45

var1 && var2 && var3
returns 0