JavaScript 中的解构(初学者到高级)
发布: (2026年3月26日 GMT+8 17:36)
3 分钟阅读
原文: Dev.to
Source: Dev.to
Without Destructuring
const user = {
name: "John",
age: 20,
city: "Mumbai"
};
const name = user.name;
const age = user.age;
const city = user.city;
console.log(name, age, city);With Destructuring
const user = {
name: "John",
age: 20,
city: "Mumbai"
};
const { name, age, city } = user;
console.log(name, age, city);Object Destructuring
基本赋值
const user = { name: 'Alice', age: 25 };
const { name, age } = user; // name = 'Alice', age = 25重命名
const user = { name: 'Alice' };
const { name: userName } = user; // userName = 'Alice'默认值
const user = {};
const { city = 'Unknown' } = user; // city = 'Unknown'嵌套解构
const profile = { id: 1, info: { email: 'a@ex.com' } };
const { info: { email } } = profile; // email = 'a@ex.com'Array Destructuring
基本赋值
const colors = ['red', 'blue', 'green'];
const [first, second] = colors; // first = 'red', second = 'blue'跳过值
const colors = ['red', 'blue', 'green'];
const [first, , third] = colors; // first = 'red', third = 'green'变量交换
let a = 4;
let b = 5;
[a, b] = [b, a]; // a = 5, b = 4工作原理
- 右侧数组
[b, a]先被求值,得到[5, 4]。 - 左侧的解构
[a, b] = [5, 4]随后把a = 5、b = 4赋值。
剩余运算符
const numbers = [1, 2, 3, 4];
const [one, ...others] = numbers; // one = 1, others = [2, 3, 4]解构的要点
- 解构 不会修改 原始对象或数组;它仅仅是提取值。
- 它创建的是 浅拷贝。嵌套的对象或数组仍然是对原始数据的引用。
const user = {
name: "Abhi",
address: {
city: "Jalandhar"
}
};
const { address } = user;
address.city = "Delhi";
console.log(user.address.city); // Delhi (original also changed)- 对
null或undefined进行解构会抛出TypeError。
const { name } = null; // TypeError结论
在 JavaScript(ES6 引入)中,解构提供了一种简洁的语法来从对象和数组中提取值,提升可读性并减少样板代码。它支持重命名、默认值、嵌套结构、剩余运算符,甚至可以在不使用临时占位符的情况下实现优雅的变量交换。