可选链(?.)和空值合并(??)运算符的作用是什么?
可选链 ?.
安全地访问深层嵌套的属性,遇到 null/undefined 时短路返回 undefined,不会报错。
// ❌ 旧写法:层层判断
const name = user && user.profile && user.profile.name
// ✅ 可选链
const name = user?.profile?.name
// 如果 user 或 user.profile 为 null/undefined → 返回 undefined
// 函数调用
const result = obj?.method?.()
// 数组索引
const first = arr?.[0]
// 动态属性名
const value = obj?.[dynamicKey]空值合并 ??
当左侧为 null 或 undefined 时返回右侧值。注意与 || 的区别:
// || 会将 falsy 值(0, '', false, null, undefined, NaN)都视为假
0 || 'default' // 'default' ❌ 不是期望的
'' || 'default' // 'default' ❌
false || 'default' // 'default' ❌
// ?? 只将 null 和 undefined 视为空
0 ?? 'default' // 0 ✅
'' ?? 'default' // '' ✅
false ?? 'default' // false ✅
null ?? 'default' // 'default' ✅
undefined ?? 'default' // 'default' ✅组合使用
// 获取用户名,如果不存在则使用匿名
const name = user?.profile?.name ?? '匿名'
// 获取配置,提供默认值
const port = config?.server?.port ?? 3000注意事项
- 不能在赋值语句左侧使用可选链:
obj?.name = 'Tom'❌ 语法错误 - 优先级:
??不能与||/&&直接混用,需要括号:(a ?? b) || c