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
相关推荐
|晴 天|2 小时前
Vue 3 + TypeScript + Element Plus 博客系统开发总结与思考
前端·vue.js·typescript
猫3283 小时前
v-cloak
前端·javascript·vue.js
旷世奇才李先生3 小时前
Vue 3\+Vite\+Pinia实战:企业级前端项目架构设计
前端·javascript·vue.js
SoaringHeart4 小时前
Flutter进阶:用OverlayEntry 实现所有弹窗效果
前端·flutter
IT_陈寒6 小时前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
herinspace6 小时前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
小码哥_常7 小时前
从MVC到MVI:一文吃透架构模式进化史
前端
嗷o嗷o7 小时前
Android BLE 的 notify 和 indicate 到底有什么区别
前端
豹哥学前端7 小时前
别再背“var 提升,let/const 不提升”了:揭开暂时性死区的真实面目
前端·面试
lar_slw7 小时前
k8s部署前端项目
前端·容器·kubernetes