ES6数组解构默认值仅在对应位置为undefined或缺失时生效,对null、0等falsy值不触发;语法为const [a, b = 'default'] = ['x'];支持跳过、嵌套及与剩余参数组合使用。

ES6 数组解构赋值中,设置默认值是防止 undefined 导致后续逻辑出错的常用手段。默认值只在对应位置的元素为 undefined(或该位置根本不存在)时生效,对 null、0、false、空字符串等 falsy 值不会触发。
数组解构默认值的基本写法
在变量声明时用 = 直接指定默认值:
-
const [a, b = 'default'] = ['x'];→a是'x',b是'default' -
const [x, , y = 'third'] = ['a', 'b'];→ 跳过第二个元素,y因位置缺失而取默认值 -
const [first, second = 10, third = 20] = [5];→first=5,second=10,third=20
默认值只响应 undefined,不响应 null 或其他 falsy 值
这是关键细节,容易被误判:
-
const [a = 'fallback'] = [null];→a是null,不是'fallback' -
const [b = 'fallback'] = [0];→b是0 -
const [c = 'fallback'] = [];→c是'fallback'(位置完全空缺,等价于undefined)
结合剩余参数与默认值的实用组合
当需要提取前几项 + 安全兜底剩余项时:
-
const [head, ...rest] = [];→head是undefined,rest是空数组[] -
const [first = 'none', ...others = []] = [];→ 显式给first和others都设默认值,避免undefined和意外的undefined数组 -
const [a, b = 100, ...c = ['x']] = [1];→a=1,b=100,c=['x']
嵌套数组解构中的默认值
多维结构里每一层都可独立设默认值:
-
const [x, [y = 99, z = 88]] = [1, [2]];→x=1,y=2,z=88 -
const [u, [v = 77]] = [1];→ 第二项是undefined,所以内层数组解构失败,v取默认值77


















