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
Use value if it exists, else assign default using the or 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 _callbacks
property does not exist for this
you will get undefined
. However if you just do a lookup on a bare name like b
, you will get a reference error if b
does not exist.
执行类似的属性查找时this._callback
,如果该_callbacks
属性不存在,this
您将获得undefined
. 但是,如果您只是在像 一样的裸名称上进行查找,b
如果b
不存在,您将收到引用错误。
One option here is to use a ternary with the typeof
operator, 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!"