JavaScript 变量回退 [英] JavaScript Variable fallback

查看:37
本文介绍了JavaScript 变量回退的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人向我解释这行代码的作用:

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:

  1. 布尔表达式的快捷方式计算(考虑a || b.如果atrue,则b 不被评估).因此,如果您分配 var v = a ||b;a 评估为可以转换为 true 的内容,然后不评估 b.
  2. 赋值语句计算为最后一个赋值(以启用var a = b = c;)
  1. The shortcut computation of boolean expressions (consider a || b. If a is true then b is not evaluated). Thus, if you assign var v = a || b; and a evaluates to something that can be cast to true, then b is not evaluated.
  2. 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屋!

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