1.数组解构赋值
const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
2.对象解构赋值
const obj = { name: 'Alice', age: 20 };
const { name, age } = obj;
console.log(name); // 'Alice'
console.log(age); // 20
3.嵌套对象的解构赋值
const obj = {
name: 'Alice',
age: 20,
address: {
city: 'Beijing',
district: 'Haidian'
}
};
const { name, age, address: { city, district } } = obj;
console.log(name); // 'Alice'
console.log(age); // 20
console.log(city); // 'Beijing'
console.log(district); // 'Haidian'
4.函数参数的解构赋值
function add([a, b]) {
return a + b;
}
add([1, 2]); // 3
5.解构赋值的默认值
const arr = [1];
const [a = 0, b = 0] = arr;
console.log(a); // 1
console.log(b); // 0
6.解构赋值的剩余语法
const arr = [1, 2, 3, 4];
const [a, b, ...rest] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4]