什么是“options = options ||” {}"在Javascript中意味着什么? [英] What does "options = options || {}" mean in Javascript?

查看:127
本文介绍了什么是“options = options ||” {}"在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆