使用双&符号&&&"进行分配 [英] Assignment with double ampersand "&&"

查看:160
本文介绍了使用双&符号&&&"进行分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚看到有人使用这段代码:

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

换句话说,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屋!

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