可选链操作符?.用于安全访问深层属性或方法:user?.profile?.address?.city;调用方法需写为data?.toString?.();配合??可提供精准默认值;支持动态键obj?.[key]和数组索引list?[0]?.name。

直接用 ?. 替代 .,中间任意一层是 null 或 undefined 就自动停住、返回 undefined,不报错也不需要手动判空。
访问对象深层属性
比如从用户数据中取城市名:
- 传统写法要层层检查:
user && user.profile && user.profile.address && user.profile.address.city - 可选链一行搞定:
user?.profile?.address?.city - 只要
user、profile或address中任一为null/undefined,整个表达式立刻返回undefined
安全调用可能不存在的方法
当不确定某个方法是否存在时,避免 is not a function 报错:
-
data?.toString?.():只有data存在且data.toString是函数,才会执行调用;否则静默返回undefined - 注意不是
data?.toString()(语法错误),必须在方法名后也加?
配合空值合并操作符 ?? 提供默认值
?. 返回 undefined 后,用 ?? 接兜底,比 || 更精准:
const city = user?.profile?.address?.city ?? '未知城市';-
??只在左侧为null或undefined时生效,不会把0、false、''当成“空”而覆盖
支持动态属性和数组索引
不止固定属性,计算属性和数组下标也能安全访问:
- 动态键:
obj?.[key],如果obj为空,不报错 - 数组元素:
list?.[0]?.name,即使list是undefined或空数组,也不会崩溃 - 注意写法是
arr?.[index],不是arr?[index](语法错误)


















