以下是使用解构赋值的所有可能方式的示例代码:
- 数组解构赋值
const array = [1, 2, 3];// 基本形式
const [a, b, c] = array;
console.log(a); // 1// 只获取部分值
const [, second] = array;
console.log(second); // 2// 设置默认值
const [d, e, f, g = 4] = array;
console.log(g); // 4// 剩余操作符
const [h, ...rest] = array;
console.log(rest); // [2, 3]
- 对象解构赋值
const person = { name: 'Alice', age: 25 };// 基本形式
const { name, age } = person;
console.log(name); // Alice// 重命名变量
const { name: personName, age: personAge } = person;
console.log(personName); // Alice// 设置默认值
const { job = 'none' } = person;
console.log(job); // none// 剩余操作符
const { name: pName, ...rest } = person;
console.log(rest); // { age: 25 }
- 嵌套结构解构赋值
const person = { name: 'Alice', age: 25, job: { title: 'developer' } };// 基本形式
const { name, job: { title } } = person;
console.log(title); // developer// 剩余操作符
const { name: pName, ...rest } = person;
console.log(rest); // { age: 25, job: { title: 'developer' } }// 深度嵌套
const { job: { title: jobTitle } = {} } = person;
console.log(jobTitle); // developer
- 函数参数解构赋值
function f([a, b]) {console.log(a, b);
}f([1, 2]); // 1 2function g({ name }) {console.log(name);
}g({ name: 'Alice', age: 25 }); // Alice