解构主要有两种形式:数组解构和对象解构。
一、数组解构
1.基本数组解构
const [first, second, third] = [1, 2, 3];
console.log(first); // 输出:1
console.log(second); // 输出:2
console.log(third); // 输出:3
2.交换变量值
数组解构的一个常见用法是交换两个变量的值。
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 输出:2
console.log(b); // 输出:1
3.解构嵌套数组
你可以对嵌套数组进行解构。
const [first, [second, third], fourth] = [1, [2, 3], 4];
console.log(first); // 输出:1
console.log(second); // 输出:2
console.log(third); // 输出:3
console.log(fourth); // 输出:4
4.解构不完全匹配数组
如果解构的变量少于数组的元素,那么剩余的元素会被忽略。
const [x, y] = [1, 2, 3];
console.log(x); // 输出:1
console.log(y); // 输出:2
5.设置默认值
如果解构的数组中的某些位置没有值,你可以为变量指定默认值。
const [first = 10, second] = [undefined, 2];
console.log(first); // 输出:10
console.log(second); // 输出:2
6.使用rest运算符
rest运算符…可以收集数组中剩余的元素到一个新的数组中。
const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 输出:1
console.log(rest); // 输出:[2, 3, 4, 5]
7.解构与迭代结合
你可以结合解构和数组的迭代方法来处理数组。
const arr = [[1, 2], [3, 4], [5, 6]];
for (const [num1, num2] of arr) {
console.log(num1, num2);
}
// 输出:
// 1 2
// 3 4
// 5 6
二、对象结构
1.基本对象解构
const person = {
name: 'Alice',
age: 30,
job: 'Engineer'
};
const { name, age, job } = person;
console.log(name); // 输出:Alice
console.log(age); // 输出:30
console.log(job); // 输出:Engineer
2.重命名属性
如果你想要将解构出来的变量重命名,可以使用冒号:来指定新的变量名。
const person = {
firstName: 'Alice',
lastName: 'Smith'
};
const { firstName: name, lastName: surname } = person;
console.log(name); // 输出:Alice
console.log(surname); // 输出:Smith
3.解构嵌套对象
当对象内部包含其他对象时,你也可以进行嵌套解构。
const user = {
name: 'Bob',
address: {
street: '123 Main St',
city: 'New York',
zip: '10001'
}
};
const { name, address: { street, city } } = user;
console.log(name); // 输出:Bob
console.log(street); // 输出:123 Main St
console.log(city); // 输出:New York
4.设置默认值
当解构的对象中某些属性不存在时,你可以为变量指定默认值。
const person = {
name: 'Alice'
};
const { name, age = 25 } = person;
console.log(name); // 输出:Alice
console.log(age); // 输出:25(因为age在person对象中不存在,所以使用默认值25)
5.解构函数返回值
当函数返回一个对象时,你可以直接在函数调用时解构这个对象。
function getPerson() {
return {
name: 'Alice',
age: 30
};
}
const { name, age } = getPerson();
console.log(name); // 输出:Alice
console.log(age); // 输出:30
6.解构剩余属性
使用剩余模式(rest pattern)…,你可以获取对象中未被解构的属性。
const person = {
name: 'Alice',
age: 30,
country: 'USA'
};
const { name, ...rest } = person;
console.log(name); // 输出:Alice
console.log(rest); // 输出:{ age: 30, country: 'USA' }
三、用途
扩展数组或者对象
const info = { name: “jobsofferings”, age: 21, email: ‘222222’ };
const infoChanged1 = { …info, email: ‘3’ };
const infoChanged2 = { email: ‘3’, …info };
console.log(…[1, 2, 3]) // 1 2 3
console.log(1, …[2, 3, 4], 5) // 1 2 3 4 5