可选链运算符(?.)解决嵌套对象属性访问时因null/undefined导致的运行时错误问题,通过在链式访问中遇空值立即返回undefined而非抛出错误,提升代码安全性与健壮性。
可选链运算符(?.)让访问嵌套对象属性时更安全:它会在遇到 null 或 undefined 时立即停止访问,并返回 undefined,而不是抛出错误。
在没有可选链之前,要安全读取 user.profile.address.city,得层层检查:
user && user.profile && user.profile.address && user.profile.address.city
一旦中间某层是 null 或 undefined(比如 user.profile 不存在),就会报 Cannot read property 'address' of undefined,整个脚本可能中断。
只需在可能为空的属性前加 ?.:
user?.profile?.address?.city —— 某一层为 null/undefined,整条表达式直接返回 undefined,不继续执行后续访问
obj?.method?.() —— 先检查 obj 是否存在,再检查 method 是否是函数,最后才调用;任一环节失败就跳过调用,不报错arr?.[index] —— 安全读取数组元素,arr 为空也不崩溃可选链只保护「点号前」的值是否为空,不处理其他错误:
user?.profile.name 中,如果 user 是 null,表达式返回 undefined;但如果 user 是对象而 profile 是字符串,profile.name 会是 undefined(不是报错),这是正常行为user?.profile?.getName() 如果 getName 存在但不是函数,仍会报 TypeError: user.profile.getName is not a function —— 可选链不校验类型,只防空值user?.name = 'Alice' 语法错误常和 ?? 搭配提供默认值:
const city = user?.profile?.address?.city ?? 'Unknown';
这样既避免崩溃,又确保有可用值,逻辑更健壮。