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
相关推荐
misty youth2 小时前
提示词合集【自用】
开发语言·前端·ai编程
战族狼魂2 小时前
Claude Code 源码泄露事件
前端·npm·node.js
We་ct2 小时前
LeetCode 67. 二进制求和:详细题解+代码拆解
前端·数据结构·算法·leetcode·typescript
还是大剑师兰特2 小时前
为什么要用 import.meta.glob 加载 SVG 图标库
开发语言·前端·javascript
渣渣xiong2 小时前
《从零开始:前端转型AI agent直到就业第三天》
前端·ai编程
qiuge6782 小时前
一网打尽react手写题(上)
前端·javascript·react.js
rhythmcc2 小时前
【npm&pnpm】基本使用
前端·npm·node.js
天天向上10242 小时前
vue3 el-date-picker 需求是想既可以输入,也可以选择, 且开始时间不能大于结束时间, 当不符合条件时border变成红色
前端·javascript·vue.js
kyle~2 小时前
前端框架---React
前端·react.js·前端框架