# 可选链操作符

可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。

?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined

与函数调用一起使用时,如果给定的函数不存在,则返回undefined

# 语法

obj?.prop // 访问对象属性
obj?.[expr]  // 表达式,如 `let nestedProp = obj?.['prop' + 'Name'];`
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

# 使用空值合并操作符

空值合并操作符可以在使用可选链时设置一个默认值:

let customer = {
  name: "Carl",
  details: { age: 82 }
};
let customerCity = customer?.city ?? "暗之城";
console.log(customerCity); // “暗之城”

# 兼容性

支持情况:Chrome 80+,Firefox 72+,Safari in IOS 13.4+,IE不支持

参考: 可选链操作符-MDN (opens new window)