美文网首页
?. and ?? 用法

?. and ?? 用法

作者: small_zeo | 来源:发表于2021-10-24 22:02 被阅读0次

一. 可选链操作符( ?. )

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
  • 函数调用:
let result = someInterface.customMethod?.();

如果希望允许 someInterface 也为 null 或者 undefined ,那么你需要像这样写

someInterface?.customMethod?.()
  • 可选链与表达式:
let nestedProp = obj?.['prop' + 'Name']
  • 可选链访问数组:
let arrayItem = arr?.[42]

二. 空值合并操作符(??)

只有当左侧为null和undefined时,才会返回右侧的数

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

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

相关文章

网友评论

      本文标题:?. and ?? 用法

      本文链接:https://www.haomeiwen.com/subject/lvlboltx.html