JavaScript (ES6+) 中的 "?." 可选链运算符用法
常用于层层递进选择,如下代码:
javascript
const user = {
profile: {
name: '小明',
address: {
city: '北京'
}
}
};
// 安全访问
const city = user?.profile?.address?.city; //city最终值=北京
const country = user?.profile?.address?.country; //country最终值 = undefined
// 与 || 结合使用
const displayCountry = user?.profile?.address?.country || '未知'; // "未知"
最终city="北京",country = undefined
访问过程为:
const city = user?.profile?.address?.city;
如果user对象存在,继续访问user.profile;如果user.profile存在,继续访问user.profile.address;如果user.profile.address存在, 继续访问user.profile.address.city,如果city有值返回,如果中间任意一步没有值 (null或 undefined),就安全的返回undefined;
与传统写法对比
javascript
// 传统写法(容易出错)
const value = obj && obj.a && obj.a.b && obj.a.b.c;
// 可选链写法
const value = obj?.a?.b?.c;
传统写法啰嗦,不够简洁。
其他多种使用方法
javascript
// 1.对象存在,属性访问,
obj?.prop
obj?.[expr] // 动态属性 const expr="name"
// 2. 函数存在,调用函数
func?.(args)
// 3. 数组存在,访问数组元素
arr?.[index]
// 4. 组合使用,
const api = {
getData: function() {
return {
result: {
value: 42
}
};
}
};
api?.getData?.()?.result?.value