js实现解构赋值
解构赋值的基本概念
解构赋值是JavaScript ES6引入的语法,允许从数组或对象中提取值并赋值给变量。这种语法简化了数据提取过程,使代码更简洁易读。
数组解构赋值
数组解构通过位置匹配进行赋值,左侧的变量名与右侧数组元素按顺序对应。
const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a, b, c); // 输出: 1 2 3
跳过某些元素可以使用逗号占位:
const [x, , z] = [10, 20, 30];
console.log(x, z); // 输出: 10 30
对象解构赋值
对象解构通过属性名匹配,变量名需与对象属性名一致。
const obj = { name: 'Alice', age: 25 };
const { name, age } = obj;
console.log(name, age); // 输出: Alice 25
重命名变量可以使用冒号语法:
const { name: userName, age: userAge } = obj;
console.log(userName, userAge); // 输出: Alice 25
默认值设置
解构时可以设置默认值,当对应值为undefined时使用默认值。
const [m = 1, n = 2] = [100];
console.log(m, n); // 输出: 100 2
const { role = 'guest' } = {};
console.log(role); // 输出: guest
嵌套解构
支持嵌套数组或对象的解构:
const nestedArr = [1, [2, 3], 4];
const [p, [q, r], s] = nestedArr;
console.log(p, q, r, s); // 输出: 1 2 3 4
const nestedObj = { info: { id: 101, status: true } };
const { info: { id, status } } = nestedObj;
console.log(id, status); // 输出: 101 true
函数参数解构
直接在函数参数中使用解构:
function greet({ name, age }) {
console.log(`Hello ${name}, you are ${age} years old.`);
}
greet({ name: 'Bob', age: 30 }); // 输出: Hello Bob, you are 30 years old.
剩余模式
使用...rest语法捕获剩余元素:

const [first, ...others] = [1, 2, 3, 4];
console.log(first, others); // 输出: 1 [2, 3, 4]
const { title, ...details } = { title: 'Book', pages: 200, author: 'Author' };
console.log(title, details); // 输出: Book { pages: 200, author: 'Author' }
注意事项
- 对象解构时若使用已声明变量,需用括号包裹整个表达式:
({ a } = obj); - 解构null或undefined会抛出TypeError,需确保数据源存在
- 解构赋值支持所有可迭代对象,包括Map、Set等






