JavaScript 变量回退 [英] JavaScript Variable fallback
问题描述
请有人向我解释这行代码的作用:
Please can someone explain to me what this line of code does:
var list = calls[ev] || (calls[ev] = {});
我最好的猜测:
它正在将变量list"设置为calls.xxx的值,其中xxx是一个变量,ev.如果 call[ev] 不存在,那么它会将它创建为一个空对象并将该空对象分配给list".是吗?
It's setting the variable "list" with the value of calls.xxx, where xxx is a variable, ev. If calls[ev] doesn't exist, then it's creating it as an empty object and assigning that empty object to "list". Is that right?
为什么要使用括号?我在哪里可以找到有关使用 || 的更多信息设置变量时,以及在这种情况下使用括号?谢谢!
Why are the parenthesis being used? Where can I find out more info on using || when setting variables, and the use of parenthesis in this context? Thanks!
推荐答案
这段代码相当于
var list;
if (calls[ev])
list = calls[ev];
else {
calls[ev] = {};
list = calls[ev];
}
使用了该语言的两个特性:
Two features of the language are used:
- 布尔表达式的快捷方式计算(考虑
a || b
.如果a
为true
,则b
不被评估).因此,如果您分配var v = a ||b;
和a
评估为可以转换为true
的内容,然后不评估b
. - 赋值语句计算为最后一个赋值(以启用
var a = b = c;
)
- The shortcut computation of boolean expressions (consider
a || b
. Ifa
istrue
thenb
is not evaluated). Thus, if you assignvar v = a || b;
anda
evaluates to something that can be cast totrue
, thenb
is not evaluated. - The assignment statement evaluates to the last assigned value (to enable
var a = b = c;
)
括号是避免这种解释所必需的:
The parentheses are necessary to avoid this interpretation:
var list = (calls[ev] || calls[ev]) = {};
(这是一个错误).
这篇关于JavaScript 变量回退的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!