JavaScript解构赋值是ES6引入的底层机制,非语法糖,支持数组/对象提取、默认值、重命名、嵌套及rest操作符,但仅浅匹配且对null/undefined报错。
JavaScript 的解构赋值不是语法糖,而是直接从数组或对象中提取值并赋给变量的底层机制。它在 ES6 中正式引入,本质是模式匹配 + 赋值的组合操作。
函数返回数组时,不用再写 const arr = fn(); const a = arr[0]; c,直接一步到位:
onst b = arr[1];
const [first, second, , fourth] = getCoordinates(); // 跳过第三个元素 const [x, y, z = 0] = [1, 2]; // z 有默认值,避免 undefined
常见错误:对 null 或 undefined 解构会报 TypeError: Cannot destructure property 'xxx' of 'yyy' as it is undefined。务必先校验来源是否为数组(Array.isArray())或使用可选链+空值合并(但注意:空值合并不适用于数组解构本身)。
接口字段名和本地变量名冲突?字段可能缺失?用冒号重命名 + 等号设默认值即可:
const { id: userId, name: fullName, role = 'user', tags = [] } = userResponse;
注意点:
role = 'user' 只在 role 属性为 undefined 时生效,null、''、0 都不会触发默认值id 在当前作用域不存在,只有 userId
{ address: { city, zip } },不能简写成 { city, zip }
尤其适合配置对象传参,让调用方更清晰、函数体更干净:
function connect({ host = 'localhost', port = 3000, timeout = 5000, secure = false }) {
console.log(`Connecting to ${secure ? 'https' : 'http'}://${host}:${port}`);
}
这种写法的问题是:如果传入 null 或 undefined,会立即报错。安全做法是加一层默认空对象:
function connect({ host = 'localhost', port = 3000 } = {}) { ... }
否则调用 connect() 就会崩,而不是走默认值。
提取前几项 + 收集剩余项,比 slice(1) 更语义化且不触发新数组拷贝(V8 引擎已优化):
const [head, ...tail] = [1, 2, 3, 4, 5]; console.log(head); // 1 console.log(tail); // [2, 3, 4, 5]
限制:
... 必须是最后一个元素,[...rest, last] 是语法错误{ ...rest, name } 不合法),但可用在嵌套中:{ user: { name, ...meta } }
最容易被忽略的是解构的“浅匹配”特性:它只处理第一层结构,深层嵌套仍需手动展开或结合其它工具(如 Lodash 的 get)。别指望 const { data: { id } } = response 在 data 为 undefined 时自动静默跳过——它照样报错。