【问题标题】:What does "?." (dot after questiion mark) mean in JS [duplicate]"?." 是什么意思(问号后的点)在JS中的意思[重复]
【发布时间】:2020-08-07 18:15:36
【问题描述】:

我偶然发现了“?”。另一个 SO 问题中的语法。像这样 -

console.log(x?.y?.z);

它有什么作用?

【问题讨论】:

  • 如何在同一秒内提问和回答?
  • @klediooo 通过勾选"Ask a Question" page底部的“回答您自己的问题”复选框。
  • 是的——我就是这么做的。不过第一次;)

标签: javascript object ecmascript-2020


【解决方案1】:

这叫Optional Chaining

它允许使用属性链接,而无需验证每个级别的属性。它在不引发异常的情况下缩短了属性评估 - 从而避免了“无法读取未定义的 X”错误。

let o = {p: {q: 'foo'}};


try {
  console.log('Trying to access the property x');
  console.log(o.x.y);
}
catch(e) {
  console.log('That was an error');
}


console.log('Trying to access the property x with Optional Chaining');

console.log(o?.x?.y);

可选链接更多用例

使用函数调用

let result = someInterface.customMethod?.();

有表达式

let nestedProp = obj?.['prop' + 'Name'];

带有数组元素

let arrayItem = arr?.[42];

ECMAScript Draft

猜你喜欢
  • 2014-07-28
  • 2017-01-12
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 2016-08-17
  • 2015-04-05
  • 2010-09-29
相关资源
最近更新 更多