浅谈ES2020 Null 判断运算符(??)

最近在重温ES6看到对象的扩展这一章时发现,阮一峰老师的Null 判断运算符解释。

为了便于检索寻找,特在博客记录。

暂时可能用不咋到,场景比较小。主要是解决我们之前的写法  AAA||BBB  如果当AAA为假时,输出BBB,如AAA为null或undefined以及空字符串或false或0,才会输出B。而且我们这种写法本身是不符合设计者初衷的。

但是场景只有null或undefinedj就需要用到此运算符了。

Null

读取对象属性的时候,如果某个属性的值是nullundefined,有时候需要为它们指定默认值。常见做法是通过||运算符指定默认值。

const headerText = response.settings.headerText || 'Hello, world!';
const animationDuration = response.settings.animationDuration || 300;
const showSplashScreen = response.settings.showSplashScreen || true;

上面的三行代码都通过||运算符指定默认值,但是这样写是错的。开发者的原意是,只要属性的值为nullundefined,默认值就会生效,但是属性的值如果为空字符串或false0,默认值也会生效。

为了避免这种情况,ES2020 引入了一个新的 Null ??。它的行为类似||,但是只有运算符左侧的值为nullundefined时,才会返回右侧的值。

const headerText = response.settings.headerText ?? 'Hello, world!';
const animationDuration = response.settings.animationDuration ?? 300;
const showSplashScreen = response.settings.showSplashScreen ?? true;

上面代码中,默认值只有在左侧属性值为nullundefined时,才会生效。

这个运算符的一个目的,就是跟链判断运算符?.配合使用,为nullundefined的值设置默认值。

const animationDuration = response.settings?.animationDuration ?? 300;

上面代码中,如果response.settingsnullundefined,或者response.settings.animationDurationnullundefined,就会返回默认值300。也就是说,这一行代码包括了两级属性的判断。

这个运算符很适合判断函数参数是否赋值。

function Component(props) {
  const enable = props.enabled ?? true;
  // …
}

上面代码判断props参数的enabled属性是否赋值,基本等同于下面的写法。

function Component(props) {
  const {
    enabled: enable = true,
  } = props;
  // …
}

??有一个运算优先级问题,它与&&||的优先级孰高孰低。现在的规则是,如果多个逻辑运算符一起使用,必须用括号表明优先级,否则会报错。

// 报错
lhs && middle ?? rhs
lhs ?? middle && rhs
lhs || middle ?? rhs
lhs ?? middle || rhs

上面四个表达式都会报错,必须加入表明优先级的括号。

(lhs && middle) ?? rhs;
lhs && (middle ?? rhs);

(lhs ?? middle) && rhs;
lhs ?? (middle && rhs);

(lhs || middle) ?? rhs;
lhs || (middle ?? rhs);

(lhs ?? middle) || rhs;
lhs ?? (middle || rhs);

Null 判断运算符兼容性

浅谈ES2020 Null 判断运算符(??)

IE和比较老的版本谷歌和火狐都不能兼容的。所以对于公众用户的程序,慎用哈。