JavaScript解构赋值直接操作右侧结构,数组按索引取值(支持跳过、默认值、剩余元素),对象按属性名匹配(支持别名、默认值、嵌套),使用时需确保右侧存在对应结构,否则报错或得undefined。

JavaScript 解构赋值不是语法糖的“花架子”,它直接操作赋值右侧的结构,按模式提取值并绑定到左侧变量——这意味着你得清楚右侧是不是真有那个结构,否则会得到 undefined 或报错。
数组解构:按索引位置提取,跳过、默认、剩余全靠逗号和三点
数组解构本质是“按序取值”,不看键名,只看位置。左边的变量顺序对应右边数组元素的索引顺序。
- 跳过某项:用连续逗号,比如
[a, , c] = [1, 2, 3]→a === 1,c === 3 - 设置默认值:在变量后加
=,仅当对应位置为undefined时生效(null不触发):[x = 10] = [null]→x === null;[x = 10] = []→x === 10 - 提取剩余元素:用
...rest放在最后,rest得到一个新数组:[first, ...rest] = [1, 2, 3, 4]→rest是[2, 3, 4] - 嵌套解构可行但易读性下降:
[a, [b, c]] = [1, [2, 3]]→b === 2
const [head, ...tail] = ['a', 'b', 'c']; console.log(head); // 'a' console.log(tail); // ['b', 'c'] const [, , third] = ['x', 'y', 'z']; console.log(third); // 'z' const [x = 5, y = 10] = [undefined, 20]; console.log(x, y); // 5, 20
对象解构:按属性名匹配,别名和默认值必须显式声明
对象解构依赖属性名精确匹配,不按顺序。如果属性不存在,默认值才生效;若用了别名,等号右边才是原始属性名。
- 基础匹配:
{ name, age } = { name: 'Alice', age: 30 }→ 直接绑定 - 别名写法:用
originalName: newName,冒号左边是源属性名,右边是目标变量名:{ title: bookTitle } = { title: 'JS Guide' } - 默认值写在别名之后:
{ count: num = 0 } = {}→num === 0;但{ count = 0 } = {}也成立(此时count是变量名也是属性名) - 嵌套解构需完整路径:
{ user: { profile: { city } } } = { user: { profile: { city: 'Tokyo' } } } - 解构参数常用于函数签名,避免
options.arg || 'default'套路:function init({ timeout = 5000, retry = 3 } = {}) { ... }—— 注意函数参数默认值也要给整个对象设默认空对象,否则传undefined会报错
const obj = { id: 123, name: 'React', tags: ['ui', 'lib'] };
const { id, name: appName, tags: [firstTag] } = obj;
console.log(id); // 123
console.log(appName); // 'React'
console.log(firstTag); // 'ui'
function connect({ host = 'localhost', port = 3000 } = {}) {
return `${host}:${port}`;
}
console.log(connect({ host: 'api.example.com' })); // 'api.example.com:3000'
常见陷阱:null/undefined、循环引用、函数参数未设默认对象
解构对输入极其敏感,很多崩溃就发生在你以为“有东西”的地方其实是个 null 或 undefined。
立即学习“Java免费学习笔记(深入)”;
-
null和undefined无法解构:执行const { x } = null直接抛TypeError: Cannot destructure property 'x' of 'null' as it is null - 安全做法是先判断或用逻辑运算符兜底:
const { name } = user || {},或用可选链 + 空值合并(但注意解构本身不支持可选链) - 函数参数解构时忘了设默认值:写成
function f({ a }) { },调用f()就崩;必须写成function f({ a } = {}) { } - 不要试图解构非对象/非数组:字符串虽可被当作类数组解构(
[a] = 'x'),但语义混乱,容易误判类型
最常被忽略的是:解构不会做类型转换,也不会“智能补全”。它只是把右侧结构里对应位置或名称的值拿出来,原样赋给左边——所以检查数据形状,永远比写得炫酷更重要。











