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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19865925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:04:55  来源:igfitidea点击:

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

javascriptvariable-assignmentor-operator

提问by Xiphias

I found this example in a book:

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

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

I simplified it so that I did not have to use a special object scope:

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

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

When b is defined, it works. When b is not defined, it does not work and throws a ReferenceError.

当 b 被定义时,它就起作用了。当 b 未定义时,它不起作用并抛出一个 ReferenceError。

ReferenceError: b is not defined

Did I do anything wrong? Thank you!

我做错了什么吗?谢谢!

回答by Andrew Clark

When performing a property lookup like this._callback, if the _callbacksproperty does not exist for thisyou will get undefined. However if you just do a lookup on a bare name like b, you will get a reference error if bdoes not exist.

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

One option here is to use a ternary with the typeofoperator, which will return "undefined"if the operand is a variable that has not been defined. For example:

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

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

回答by KooiInc

It should work in this form:

它应该以这种形式工作:

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