如果存在值,则使用值,否则使用 or 运算符分配默认值

Use value if it exists, else assign default using the or operator

本文关键字:分配 默认值 运算符 如果 存在 or      更新时间:2023-09-26

我在一本书中找到了这个例子:

// Create _callbacks object, unless it already exists
var calls = this._callbacks || (this._callbacks = {});

简化了它,这样我就不必使用特殊的对象范围:

var a = b || (b = "Hello!");

当定义 b 时,它起作用。如果未定义 b,它不起作用并抛出 ReferenceError。

ReferenceError: b is not defined

我做错了什么吗?谢谢!

在执行像 this._callback 这样的属性查找时,如果 _callbacks 属性不存在this,您将得到undefined。 但是,如果您只是对像 b 这样的裸名称进行查找,如果不存在b,您将收到引用错误。

这里的一种选择是将三元与 typeof 运算符一起使用,如果操作数是尚未定义的变量,它将返回 "undefined"。 例如:

var a = typeof b !== "undefined" ? b : (b = "Hello!");

它应该以这种形式工作:

var b, a = b || (b = "Hello!", b);
//  ^ assign b
//                           ^ () and , for continuation
//                             ^ return the new value of b
//=>  result: a === b = "Hello!"