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
相关推荐
pan_junbiao11 小时前
Go 语言基本数据类型
java·前端·golang
ZhengEnCi19 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
kyriewen20 小时前
我给 61 个前端库排了两次名,最多差了 46 位
前端·javascript·程序员
亲亲小宝宝鸭20 小时前
Cesium启动:TLE数据是如何变成轨迹线的
前端·cesium
阿里云云原生20 小时前
对话即构建,在 AgentCore 构建 Agent 就是这么简单
前端·agent
夕水21 小时前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript
狗头大军之江苏分军1 天前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬1 天前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
parade岁月1 天前
VTable Guild 3.0.0 发布,面向 Vue 3 的 ProTable 式业务表格
前端
xurileidian1 天前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python