可选链式操作符
可选链式操作符允许读取被连接对象的深层次的属性的值而无需明确校验链条上每一个引用的有效性
let nestedProp = obj.first?.second;
//等价于
let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
像上面这行代码解读为
如果
obj.first
存在,则取obj.first
中的second
,如果不存在,则返回undefined
我们也可以使用如下方法来判断obj.first
是否存在来取得obj.first.second
的值
let nestedProp = obj.first&&obj.first.second;
但这种方法的缺陷就是必须要保证obj.first
既不是null
也不是undefined
。如果只是直接访问 obj.first.second
,而不对 obj.first
进行校验,则有可能抛出错误。