【JS进阶】对象解构与数组解构
JavaScript 数组解构
数组解构(Destructuring Assignment)是ES6引入的一种语法,可以快速从数组或可迭代对象中提取值并赋值给变量。
一、基本用法
// 基础解构
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor, thirdColor] = colors;
console.log(firstColor); // 'red'
console.log(secondColor); // 'green'
console.log(thirdColor); // 'blue'
二、高级用法
1. 跳过某些元素
const numbers = [1, 2, 3, 4];
const [first, , third] = numbers;
console.log(first); // 1
console.log(third); // 3
2. 默认值
const fruits = ['apple'];
const [fruit1, fruit2 = 'banana'] = fruits;
console.log(fruit1); // 'apple'
console.log(fruit2); // 'banana' (默认值)
3. 剩余元素
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
4. 变量交换
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
5. 嵌套数组解构
const colors = ['red', ['green', 'lightgreen'], 'blue'];
const [first, [second, third]] = colors;
console.log(first); // 'red'
console.log(second); // 'green'
console.log(third); // 'lightgreen'
三、实际应用场景
1. 函数返回多个值
function getSizes() {
return [10, 20, 30];
}
const [small, medium, large] = getSizes();
2. 正则表达式匹配
const url = 'https://example.com/users/123';
const matches = url.match(/^https?:\/\/([^/]+)\/users\/(\d+)$/);
if (matches) {
const [, domain, userId] = matches;
console.log(domain); // 'example.com'
console.log(userId); // '123'
}
3. 与迭代器配合使用
const map = new Map();
map.set('name', 'John');
map.set('age', 30);
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
// 输出:
// name: John
// age: 30
JavaScript 对象解构
对象解构(Destructuring Assignment)是ES6引入的一种语法,可以快速从对象中提取属性值并赋值给变量。
一、基本用法
// 基础解构
const person = { name: 'Alice', age: 25, job: 'Developer' };
const { name, age, job } = person;
console.log(name); // 'Alice'
console.log(age); // 25
console.log(job); // 'Developer'
二、高级用法
1. 别名赋值
const user = { id: 1, username: 'jsmith' };
const { username: login } = user;
console.log(login); // 'jsmith'
// console.log(username); // ReferenceError
2. 默认值
const options = { width: 100 };
const { width = 800, height = 600 } = options;
console.log(width); // 100 (使用已有值)
console.log(height); // 600 (使用默认值)
3. 嵌套对象解构
const employee = {
name: 'Bob',
position: {
title: 'Manager',
department: 'IT'
}
};
const {
name,
position: { title, department }
} = employee;
console.log(name); // 'Bob'
console.log(title); // 'Manager'
console.log(department); // 'IT'
4. 剩余属性
const student = { name: 'Tom', age: 20, grade: 'A', school: 'XYZ' };
const { name, ...rest } = student;
console.log(name); // 'Tom'
console.log(rest); // { age: 20, grade: 'A', school: 'XYZ' }
5. 动态属性名解构
const key = 'username';
const { [key]: user } = { username: 'admin' };
console.log(user); // 'admin'
三、实际应用场景
1. 函数参数解构
function greet({ name, age }) {
console.log(`Hello, ${name}. You are ${age} years old.`);
}
greet({ name: 'Alice', age: 25 });
2. 配置对象处理
function createElement({ tag = 'div', content = '', classes = [] }) {
const el = document.createElement(tag);
el.textContent = content;
el.classList.add(...classes);
return el;
}
const myDiv = createElement({
content: 'Hello',
classes: ['box', 'highlight']
});
3. 模块导入
// 代替 const fs = require('fs'); const path = require('path');
const { readFile, writeFile } = require('fs');
const { join, basename } = require('path');
4. React props 解构
function UserCard({ user: { name, avatar }, onClick }) {
return (
<div onClick={onClick}>
<img src={avatar} alt={name} />
<h3>{name}</h3>
</div>
);
}
四、注意事项
-
解构不存在的属性会得到
undefined
const { missing } = {}; console.log(missing); // undefined
-
解构
null
或undefined
会报错const { prop } = null; // TypeError const { prop } = undefined; // TypeError
-
解构赋值可以与数组解构混合使用
const { props: [first, second] } = { props: [1, 2] }; console.log(first, second); // 1 2
-
解构时可以计算属性名
const prop = 'name'; const { [prop]: myName } = { name: 'Alice' }; console.log(myName); // 'Alice'