一、数组解构:按位置匹配 🎯
1. 基础用法
数组解构通过位置匹配来赋值:
let [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
2. 跳过元素与剩余值
用逗号跳过元素,或用 ... 收集剩余值:
let [, , third] = ["foo", "bar", "baz"];
console.log(third); // "baz"
let [head, ...tail] = [1, 2, 3, 4];
console.log(tail); // [2, 3, 4]
3. 默认值
当解构不成功时,变量为 undefined,但可以设置默认值:
let [x = 1, y = 2] = [10];
console.log(x, y); // 10 2(y 使用默认值)
let [m = 1] = [null];
console.log(m); // null(默认值仅在 undefined 时生效)
二、对象解构:按属性名匹配 🔑
1. 基础用法
变量名需与属性名一致,或通过别名映射:
let { name, age } = { name: "Alice", age: 20 };
console.log(name, age); // Alice 20
// 别名用法
let { name: userName } = { name: "Bob" };
console.log(userName); // Bob
2. 嵌套解构
支持多层嵌套结构,但需确保父属性存在:
let user = {
profile: {
address: "Mars",
hobbies: ["coding", "music"],
},
};
let {
profile: {
address,
hobbies: [firstHobby],
},
} = user;
console.log(address, firstHobby); // Mars coding
3. 默认值与错误处理
let { x = 3, y = 5 } = { x: 1 };
console.log(x, y); // 1 5
// 若父属性不存在,会报错!
let { foo: { bar } } = {}; // ❌ TypeError
三、其他类型的解构 🌟
1. 字符串解构
字符串会被视为类数组对象:
let [a, b] = "hi";
console.log(a, b); // h i
let { length: len } = "hello";
console.log(len); // 5
2. 函数参数解构
灵活处理函数参数:
// 数组参数
function sum([x, y = 0]) {
return x + y;
}
console.log(sum([10])); // 10
// 对象参数
function greet({ name = "User", age }) {
return `Hello ${name}, you are ${age} years old!`;
}
console.log(greet({ age: 25 })); // Hello User, you are 25 years old!
四、解构赋值的妙用 💡
1. 变量交换
无需中间变量:
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
2. 提取 JSON 数据
快速提取 JSON 中的字段:
const jsonData = {
id: 42,
status: "OK",
data: [100, 200],
};
let { id, status, data: numbers } = jsonData;
console.log(id, status, numbers); // 42 OK [100, 200]
3. 导入模块方法
简化模块方法的使用:
const { log, sin } = Math;
console.log(log(sin(Math.PI / 2))); // 0
console.log(sin(Math.PI / 2)); // 1
五、注意事项 ⚠️
- 严格匹配:解构失败时变量为
undefined。 - 默认值惰性求值:默认值为表达式时,仅在需要时执行。
- 已声明变量需加括号:
let x; ({ x } = { x: 10 }); // ✅ 正确
结语 🚀
解构赋值是 JavaScript 中一项强大的语法,它让代码更简洁、逻辑更清晰。无论是处理 API 返回的数据,还是简化函数参数传递,都能大显身手。掌握它,让你的代码焕然一新!