lostvita / blog

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TC39提案:空值合并

lostvita opened this issue · comments

原文:tc39/proposal-nullish-coalescing

概述

提案阶段:Stage 2
作者:Gabriel Isenberg、Daniel Ehrenberg

当使用可选链在一个嵌套结构的对象中访问某个属性时,我们通常希望当属性的结果值为 nullundefined 时它可以返回一个默认值,目前我们一贯的做法是:

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

const undefinedValue = response.settings?.undefinedValue || 'default val'  // result: default val
const nullValue = response.settings?.nullValue || 'default val'  // result: default val

这种方式通常在值为 nullundefined 的情况下可以很好地运行,但这在当一些值为假的时候可能会产生意想不到的结果:

const headerText = response.settings?.headerText || 'Hello, world!'  // result: 'Hello, world!'
const animationDuration = response.settings?.animationDuration || 300 // result: 300
const showSplashScreen = response.settings?.showSplashScreen || true // result: true

空值合并旨在更好地处理这些情况,并对空值进行严格等性检查(nullundefined)。

语法

如果 ?? 左边的表达式为 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