可选链操作符(?.)能安全访问深层属性,避免因null或undefined导致的错误。以前需用多重判断或try-catch检查user && user.profile && user.profile.settings,代码冗长;现可简写为const theme = user?.profile?.settings?.theme,任一环节缺失即返回undefined。常与空值合并操作符(??)结合使用,如const theme = user?.profile?.settings?.theme ?? 'light',确保返回默认值。此外,可选链还支持方法调用obj.method?.()和数组访问arr?.[0],显著减少防御性代码,提升开发效率。

可选链操作符(?.)让访问深层嵌套对象属性变得更安全、更简洁。以前在访问如 user.profile.settings.theme 这样的深层属性时,如果中间某个层级为 null 或 undefined,就会抛出错误。现在使用可选链,可以自动检查每一层是否存在。
避免 TypeError 的传统方式
没有可选链时,通常需要用多重条件判断:
if (user && user.profile && user.profile.settings) {
const theme = user.profile.settings.theme;
}
或者使用 try-catch,代码冗长且不易读。
使用可选链简化访问
现在可以直接写成:
立即学习“Java免费学习笔记(深入)”;
const theme = user?.profile?.settings?.theme;
如果 user、profile 或 settings 中任意一个是 null 或 undefined,表达式会立即返回 undefined,不会报错。
结合空值合并操作符更强大
常和空值合并操作符(??)搭配使用,提供默认值:
const theme = user?.profile?.settings?.theme ?? 'light';
这样即使路径不存在或值为 undefined,也能得到一个合理的默认主题。
基本上就这些。可选链不仅适用于属性访问,还可用于方法调用(obj.method?.())和数组(arr?.[0]),大幅减少防御性编程的样板代码。










