三个ES2020新特性记录

628 阅读3分钟

逻辑 OR 赋值 (||=)

  • 逻辑OR赋值(x||=y),只在x为假时赋值
const a = { duration: 50, title: '' };

a.duration ||= 10;
console.log(a.duration);
// expected output: 50

a.title ||= 'title is empty.';
console.log(a.title);
// expected output: "title is empty"

返回x,在x为真时;返回y,在x为假时。

  • 不等于x=x||y

可选链操作符(?.)Optional chaining

  • 允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。
const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
console.log(adventurer.cat?.name)
  • 引用对象,寻找潜在子属性时,不必考虑父级元素是否为null或者undefined,而不必考虑抛出错误,无需检验父级的状态
let nestedProp = obj.first?.second;

等价于

let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
  • 引用方法,调用一个可能不存在的方法时也可以使用可选链。这将是比较有用的,例如,当使用一个 API 的方法可能不可用时,因为当前用户的设备不可用支持该功能。
  • 函数调用时如果被调用的,使用任选链可以使表达式自动返回undefined而不是方法抛出一个异常。
let result = someInterface.customMethod?.();
  • 注意:如果存在一个名且不是函数,使用 ?.属性会产生一个 TypeError异常(x.y is not a function)。

  • 注意:如果someInterface 自己是null或者undefined,异常 TypeError还会被抛出 someInterface is null 如果你希望 someInterface也为null或者undefined,那么你需要像这样写 someInterface?.customMethod?.()

  • 事件处理器

//  ES2019的写法
function doSomething(onContent, onError) {
  try {
    // ... do something with the data
  }
  catch (err) {
    if (onError) { // 校验onError是否真的存在
      onError(err.message);
    }
  }
}
// 使用可选链进行函数调用
function doSomething(onContent, onError) {
  try {
   // ... do something with the data
  }
  catch (err) {
    onError?.(err.message); // 如果onError是undefined也不会有异常
  }
}
  • 可选链和表达式 当使用方括号与属性名的形式来访问属性时,你也可以使用可选链操作符:
let nestedProp = obj?.['prop' + 'Name'];
  • 可选链不能用于赋值
let object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
  • 可选链访问数组元素
let arrayItem = arr?.[42];

空值合并运算符??

  • 空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
  • 与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,'' 或 0)时。见下面的例子。
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
  • 用空值合并运算在逻辑正确的前提下,代码更加简洁。空值合并运算符 与 可选链 相结合,可以很轻松处理多级查询并赋予默认值问题。