← 中文资源

简体中文版本

optional chaining 深层取值短路

链路中任何一环为 null/undefined 时整条表达式短路成 undefined:?.() 让缺失的方法调用不抛错,配合 ?? 给默认值,层层判空的样板代码全部消失。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

city: Hangzhou
phone: undefined
send: sent
cancel: undefined
city fallback: Hangzhou
phone fallback: no phone
missing branch: true

实现说明

order、notifier 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 演示输出是带标签的(city:、phone:、send:),每个操作都会留下自己的一行标注。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。 跨调用保留的状态放在这些顶层绑定里:order、notifier。

核心语句

const notifier = { send() { return 'sent'; } };

代码示例

// 链路中任何一环是 null/undefined,整个表达式短路成 undefined,不再层层判空
const order = { customer: { address: { city: 'Hangzhou' } } };
console.log('city:', order.customer?.address?.city);
console.log('phone:', order.customer?.phone?.number);

// 可选调用 ?.():方法不存在时不抛错,返回 undefined
const notifier = { send() { return 'sent'; } };
console.log('send:', notifier.send?.());
console.log('cancel:', notifier.cancel?.());

// 与空值合并搭配:短路出的 undefined 落到默认值
console.log('city fallback:', order.customer?.address?.city ?? 'unknown');
console.log('phone fallback:', order.customer?.phone?.number ?? 'no phone');

// 断链的证据:缺失分支返回 undefined,而不是抛 TypeError
console.log('missing branch:', order.customer?.phone?.verified === undefined);