1.(?. )的使用
可选链操作符(?.)允许读取位于连接对象链深处的属性值,而不必明确验证链中的每个引用是否有效。
let nestedProp = obj.first && obj.first.second;
// 等价于
let nestedProp = obj.first?.second;
js会在尝试访问obj.first.second之前隐式的检查并确定obj.first既不是null也不是undefined。如果obj.first是null或者undefined,表达式将会短路计算直接返回undefined
2.(??)的使用
空值合并操作符,可以在使用可选链时设置一个默认值
let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "北京";
console.log(customerCity); // “北京”
3.语法
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
更多用法可参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining