ES6 中的 “?.” 可选链运算符用法

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
相关推荐
恋猫de小郭18 分钟前
Flutter 3.50 & Dart 3.14 发布,快来看看有什么更新吧
android·前端·flutter
非优秀程序员8 小时前
第10章 千团出世|《互联网产品恩仇录》
前端
非优秀程序员8 小时前
第11章 小高在对面|《互联网产品恩仇录》
前端
非优秀程序员8 小时前
第14章 只剩美团|《互联网产品恩仇录》
前端
非优秀程序员8 小时前
第09章 老乡何必为难老乡|《互联网产品恩仇录》
前端
非优秀程序员8 小时前
第03章 三大门户,烽烟起于瀛海威|《互联网产品恩仇录》
前端
曦樂~12 小时前
【Web Development】02 CSS
前端·css
风骏时光牛马12 小时前
后端服务接口开发与数据逻辑处理
前端
东鹏特饮13 小时前
经典打砖块(Breakout)游戏
前端·css·css3
IT_陈寒13 小时前
Vite的HMR把我整不会了:一个生产环境的热更新坑
前端·人工智能·后端