什么是“options = options ||” {}"在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
设置为值选项
如果存在,则设置为空对象。
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
不带参数,选项
将使用空对象初始化。
If you call test
without arguments, options
will be initialized with an empty object.
逻辑OR ||
运算符将返回其第二个操作数,如果第一个操作数是 falsy 。
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
.
这篇关于什么是“options = options ||” {}"在Javascript中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!