对象解构默认值仅对 undefined 生效,null 等 falsy 值不触发;需用 ?? {} 或 || {} 为源对象兜底;嵌套解构须逐层设默认值;处理 null 字段宜先用 ?? 归一化;函数参数解构应带 = {} 防 undefined 报错。

对象解构设置默认值,核心是让变量在对应属性为 undefined 时自动 fallback,但必须注意:默认值只对 undefined 生效,null、0、false、空字符串等“falsy 值”不会触发。
最外层必须兜底对象
如果源对象本身可能是 null 或 undefined,解构前必须先提供一个安全的兜底对象(如 || {} 或 ?? {}),否则会直接报错 Cannot destructure property 'x' of undefined:
const { name = '游客', age = 18 } = userData || {};- 推荐用
?? {}更精准(区别于||,它只在null/undefined时生效):const { name = '游客' } = userData ?? {};
嵌套层级要逐层设默认值
中间某一层缺失(比如 user.profile 是 undefined),后续解构就会崩。必须给每一级可能为空的对象设默认值:
- 错误写法(
user.profile.avatar中任意一层为undefined就报错):const { user: { profile: { avatar: { url } } } } = data; - 正确写法(每层都加
= {}):const { user = {} } = data; const { profile = {} } = user; const { avatar = {} } = profile; const { url } = avatar; - 或一步嵌套(可读性略低,但合法):
const { user: { profile: { avatar: { url } = {} } = {} } = {} } = data ?? {};
处理 null 字段要用 ?? 预处理
接口返回的字段可能是 null(例如 avatar: null),而默认值对 null 不生效。这时需先用空值合并操作符归一化:
-
const { avatar } = userData ?? {};→ 若后端返回{ avatar: null },解构后avatar仍是null - 安全做法:
const { avatar = {} } = { ...userData, avatar: userData?.avatar ?? {} } ?? {}; - 更简洁:
const { avatar } = userData ?? {}; const { url } = avatar ?? {};
函数参数中直接解构 + 默认值
传配置对象的函数,别在函数体内反复判断 options.title || '默认',直接在形参位置完成解构和默认值:
function render({ title = '标题', size = 'md', theme = 'light' } = {}) { ... }-
= {}是关键——防止调用时传了undefined导致整个解构失败 - 支持部分传参:
render({ title: '首页' }),其余自动取默认











