使用双&符号&&&"进行分配 [英] Assignment with double ampersand "&&"
问题描述
我刚看到有人使用这段代码:
I just saw someone use this piece of code:
ctx = canvas.getContext && canvas.getContext('2d');
双安瓿如何在这种情况下起作用?它不只是将true分配给ctx变量吗?
How does the double ampersand work in this context? Would it not just assign "true" to the ctx variable?
推荐答案
这是确保您的函数存在之前的常用方法你叫它。
This is a common way to make sure your function exists before you call it.
它的工作原理如下(来自 developer.mozilla.com ):
It works like this (From developer.mozilla.com):
expr1&& expr2
如果可以转换为false
,则返回expr1
;否则,返回expr2
。因此,当与布尔值一起使用时,如果两个操作数都是,
;否则,返回&&
将返回true
真false
。
expr1 && expr2
Returnsexpr1
if it can be converted tofalse
; otherwise, returnsexpr2
. Thus, when used with Boolean values,&&
returnstrue
if both operands aretrue
; otherwise, returnsfalse
.
换句话说,Javascript不强制除非必须,否则操作数应为布尔值。
In other words, Javascript does not coerce the operands to boolean values unless it has to.
4&& 5
返回5,不是真的。
4 && 5
Returns 5, not true.
在你的情况下,如果第一个表达式是 undefined
(可以转换为false),那么 ctx
将为false,并且不会评估第二个表达式。如果第一个表达式是一个函数(不能转换为 false
),那么Javascript将计算第二个表达式,并将其值赋给 ctx
变量。
In your case, if the first expression is undefined
(which is convertible to false), then ctx
will be false, and the second expression does not get evaluated. If the first expression is a function (which cannot be converted to false
), then Javascript evaluates the second expression, and assigns it's value to the ctx
variable.
这篇关于使用双&符号&&&"进行分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!