JavaScript - 空位合并运算符

2019-07-27 · xiejiahe

?? 是一种新的运算符,目前在 Stage3阶段中,很快就面世了。

概述

执行访问属性时,如果该属性访问的结果是nullundefined,通常需要给出一个默认值,目前在JavaScript中常见的做法是使用 || 运算符, 参见如下代码:

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings.undefinedValue || 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue || 'some other default'; // result: 'some other default'

上面的代码只适用于 nullundefined ,但有一些虚假值可能会产生令人惊讶的结果:

const headerText = response.settings.headerText || 'Hello, world!'; // Potentially unintended. '' is falsy, result: 'Hello, world!'
const animationDuration = response.settings.animationDuration || 300; // Potentially unintended. 0 is falsy, result: 300
const showSplashScreen = response.settings.showSplashScreen || true; // Potentially unintended. false is falsy, result: true

由于隐式转换的原因 '' / 0 / false 都会被转换为 false, 执行结果都会为给出的默认值,但通常我们并不想要这样的结果。

句法

如果 ?? 运算符左侧的表达式求值为 nullundefined,则返回其右侧结果。

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false

最后

?? 只是一种语法糖,没过多久各种工具都会加入其中,马上就能看到项目一堆 ??了,哈哈。

可能有人觉得 ?? 非常别扭,可读性低,但是这种操作符在其他语言中早就有了, 例如 php7 就已经存在这种操作符。

JavaScript
原创文章,转载请注明出处。