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
相关推荐
程序员黑豆3 小时前
Java类型推断完全指南:从var到菱形运算符,掌握使用限制与最佳实践
java·前端·ai编程
To_OC4 小时前
踩了个 TS 的坑之后,我终于把 type 和 interface 掰明白了
前端·react.js·typescript
GreenTea4 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
浮生望4 小时前
前端API工程化:用 Mock 数据与 Axios 配置实现独立于后端的并行开发
前端
万少5 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
波波0075 小时前
C# 15 重磅新特性: 带标签 break 与 continue:重新定义嵌套循环控制流
服务器·前端·c#
Brown.alexis6 小时前
es6知识点1-自备使用
前端·ecmascript·es6
小爬的老粉丝7 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
计算机魔术师7 小时前
新兴多智能体系统的模式与问题
前端
用户059540174468 小时前
AI Agent 上下文污染踩坑实录:用 pytest + Redis 揪出 3 类记忆串号 bug,排查 6 小时
前端·css