默认值仅在对应位置为undefined时生效,null、0、false、空字符串等falsy值均不触发;嵌套解构需结构匹配,rest元素必须居末且不可设默认值。

数组解构赋值能快速提取数据,但默认值只在对应位置为 undefined 时生效,对 null、0、false、空字符串等“falsy 值”不触发。
默认值只响应 undefined
写法如 const [a = 10, b = 20] = arr,其中:
-
a取值失败(即arr[0]是undefined)时才用10 -
arr[0] === null→a仍是null,不会变成10 -
arr[0] === 0或arr[0] === ''→ 同样不触发默认值
嵌套数组安全提取要逐层匹配结构
比如从 [[1, 2], [3]] 中取第二项的首元素:
- ✅ 正确:
const [, [secondFirst = 'missing']] = [[1, 2], [3]];→secondFirst === 3 - ✅ 防空子数组:
const [, [x = 'no-x'] = []] = [[1, 2], []];→x === 'no-x' - ❌ 错误:
const [, [y = 'fail']] = [[1, 2], null];→ 报错:Cannot destructure property '0' of 'null'
配合 rest 元素处理不定长数组
rest 元素(...)必须放在最后,不能设默认值,但其内部可再解构:
- 提取头尾 + 收集中间:
const [first, ...middle, last] = [10, 20, 30, 40];→first=10,middle=[20,30],last=40 - 带默认兜底:
const [x = 'x', ...rest] = [];→x='x',rest=[] - 注意:
const [...items = ['default']] = [];❌ 语法错误,rest 本身不能设默认值
常见陷阱与规避建议
实际使用中容易踩坑的地方:
- 空数组
[]是合法值,不会触发默认值,也不等于“缺失” - 跳过某位(如
[,,c])后,若该位置不存在,c是undefined,此时可加默认值[,,c = 'none'] - 多维结构建议先确认源数据形状,再写解构模式;调试时可先
console.log(arr)再动手

















