[JS Daily] ES6 解构赋值:让代码更简洁的魔法语法 (缩进修复版)
ES6 解构赋值:让代码更简洁的魔法语法
日期:2026-02-28 | 难度:⭐⭐ 初级
📖 什么是解构赋值?
解构赋值是 ES6 引入的语法糖,可以从数组或对象中提取值,并赋值给变量。
🔍 数组解构
// 旧写法 - 需要多行提取
const arr = [1, 2, 3];
const a = arr[0];
const b = arr[1];
const c = arr[2];
// ✅ 解构写法 - 一行完成
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
跳过元素
const [first, , third] = [1, 2, 3]; // 跳过第二个元素
console.log(first, third); // 1 3
默认值
const [x = 10, y = 20] = [5]; // y 使用默认值 20
console.log(x, y); // 5 20
🏗️ 对象解构
const user = { name: 'Alice', age: 25, city: 'Beijing' };
// 提取属性
const { name, age } = user;
// 重命名:提取 name 并赋值给 userName
const { name: userName } = user;
// 默认值:如果 country 不存在,使用 'China'
const { country = 'China' } = user;
🎯 实际应用
1. 函数参数解构
// ❌ 旧写法:需要从对象中反复取值
function greetOld(user) {
return `Hello, ${user.name}!`;
}
// ✅ 解构写法:直接在参数中提取
function greet({ name, age }) {
return `Hello, ${name}! You are ${age} years old.`;
}
2. React Hooks
import { useState } from 'react';
const [count, setCount] = useState(0); // 解构 useState 返回的数组
const [user, setUser] = useState(null); // 第一个元素是值,第二个是 setter
💡 高级技巧
嵌套解构
// 深层嵌套对象
const data = {
user: {
profile: {
name: 'Charlie',
location: { city: 'Shanghai' }
}
}
};
// 嵌套解构语法:逐层展开
const { user: { profile: { name, location: { city } } } } = data;
console.log(name, city); // Charlie Shanghai
剩余运算符 ...
数组剩余元素:
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...restOfTheNumbers] = numbers;
console.log(restOfTheNumbers); // [3, 4, 5]
对象剩余属性:
const person = { name: 'David', age: 25, city: 'NYC' };
const { name, ...otherInfo } = person;
console.log(otherInfo); // { age: 25, city: 'NYC' }
📚 速查表
数组解构:const [a, b] = [1, 2];
对象解构:const {name, age} = {name: 'Tom', age: 25};
默认值:const [x = 10] = []; // x = 10
重命名:const {name: n} = {name: 'Tom'};
嵌套:const {a: {b}} = {a: {b: 1}};
剩余:const [first, ...rest] = arr;
明日预告:ES6 箭头函数与普通函数的区别
本系列每天分享一个 JavaScript 知识点,欢迎关注!
评论
发表评论