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

工作原理

  1. 右侧数组 [b, a] 先被求值,得到 [5, 4]
  2. 左侧的解构 [a, b] = [5, 4] 随后把 a = 5b = 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)
  • nullundefined 进行解构会抛出 TypeError
const { name } = null; // TypeError

结论

在 JavaScript(ES6 引入)中,解构提供了一种简洁的语法来从对象和数组中提取值,提升可读性并减少样板代码。它支持重命名、默认值、嵌套结构、剩余运算符,甚至可以在不使用临时占位符的情况下实现优雅的变量交换。

0 浏览
Back to Blog

相关文章

阅读更多 »

什么是 JS 中的循环

在 JavaScript 中进行循环非常有用,当你想要一次又一次地执行相同的任务而不必重复编写相同的代码时。类型有…

网络怀旧

概述 我一直对互联网的快速演变感到着迷。从90年代那种杂乱、色彩斑斓的网站,到今天的简洁、极简设计——它……

Show HN: 字母时钟

请提供您希望翻译的具体摘录或摘要内容,我才能为您进行翻译。