阅读 11

ECMA-262

ECMAScript新语法,统称ECMA-262

表达式和运算符

可选链操作符(Optional Chaining)

语法

obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)

示例

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
复制代码

空值合并运算符(Nullish coalescing Operator)

语法

leftExpr ?? rightExpr

示例

const foo = null ?? 'default string';
console.log(foo); // expected output: "default string"

const bar = undefined ?? 'default string';
console.log(bar); // expected output: "default string"

const baz = 0 ?? 42;
console.log(baz); // expected output: 0

const qux = '' ?? 42;
console.log(qux); // expected output: ''
复制代码
关注下面的标签,发现更多相似文章
评论