Skip to content

Optional Chaining

一句话解释

可选链(?.)仅在左侧非 null 且非 undefined 时访问属性,否则返回 undefined。

用大白话说

可选链(?.)让你安全访问深层嵌套属性,无需一长串 if 检查。若 ?. 左侧为 null 或 undefined,整个表达式短路并返回 undefined,而非抛出 TypeError。在可选链出现前,访问 user.address.city 需检查 user && user.address && user.address.city。有了可选链,写 user?.address?.city——任一环节为 nullish,结果即 undefined。更短、更清晰、更不易错。可选链适用于属性(obj?.prop)、方法调用(obj?.method())和函数调用(func?.())。它还有方括号形式(obj?.[key])。它在 ES2020 加入,是最受喜爱的现代 JavaScript 特性之一。

示例

javascript
const user = { name: "Ada", address: { city: "London" } };

console.log(user?.address?.city);    // "London"
console.log(user?.contact?.phone);   // undefined (no throw)

// Without optional chaining this throws:
// console.log(user.contact.phone); // TypeError

const arr = null;
console.log(arr?.length); // undefined

?. 在左侧为 null/undefined 时短路为 undefined,而非抛异常。整条链在第一个 nullish 环节停止。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表