什么是“选项=选项||"{}"在 Javascript 中是什么意思? [英] What does "options = options || {}" mean in Javascript?
问题描述
前几天我看到了一段我很好奇的代码,但我不确定它到底做了什么;
I came over a snippet of code the other day that I got curious about, but I'm not really sure what it actually does;
options = options || {};
到目前为止我的想法;将变量 options
设置为值 options
如果存在,如果不存在,则设置为空对象.
My thought so far; sets variable options
to value options
if exists, if not, set to empty object.
是/否?
推荐答案
这对于将默认值设置为函数参数很有用,例如:
This is useful to setting default values to function arguments, e.g.:
function test (options) {
options = options || {};
}
如果不带参数调用 test
,options
将被初始化为一个空对象.
If you call test
without arguments, options
will be initialized with an empty object.
如果第一个操作数是falsy,则逻辑 OR ||
运算符将返回其第二个操作数.
The Logical OR ||
operator will return its second operand if the first one is falsy.
Falsy 值为:0
、null
、undefined
、空字符串(""
)、NaN
,当然还有 false
.
Falsy values are: 0
, null
, undefined
, the empty string (""
), NaN
, and of course false
.
ES6 更新:现在,我们有了真正的 默认参数值 自 ES6 以来的语言.
ES6 UPDATE: Now, we have real default parameter values in the language since ES6.
function test (options = {}) {
//...
}
如果您不带参数调用该函数,或者使用值 undefined
显式调用该函数,则 options
参数将采用默认值.与 ||
运算符示例不同,其他虚假值不会导致使用默认值.
If you call the function with no arguments, or if it's called explicitly with the value undefined
, the options
argument will take the default value. Unlike the ||
operator example, other falsy values will not cause the use of the default value.
这篇关于什么是“选项=选项||"{}"在 Javascript 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!