【ES6新特性】解构赋值常见用法
ES6解构赋值用法详解
一、解构赋值基础概念
解构赋值(Destructuring Assignment)是ES6新增的语法,可以快速从数组或对象中提取值并赋给变量。
1.1 传统取值方式 vs 解构赋值
// 传统方式
const arr = [1, 2, 3];
const a = arr[0];
const b = arr[1];
// 解构赋值
const [x, y] = [1, 2, 3];
console.log(x); // 1
console.log(y); // 2
二、对象解构赋值
2.1 基本对象解构
const user = {
name: 'Alice',
age: 28,
address: 'Beijing'
};
// 解构赋值
const { name, age } = user;
console.log(name); // Alice
console.log(age); // 28
2.2 重命名变量
const { name: userName, age: userAge } = user;
console.log(userName); // Alice
2.3 嵌套对象解构
const company = {
name: 'TechCo',
founder: {
firstName: 'Bob',
lastName: 'Smith'
}
};
const {
founder: { firstName }
} = company;
console.log(firstName); // Bob
三、数组解构赋值
3.1 基础数组解构
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;
console.log(firstColor); // red
3.2 跳过元素
const [, , thirdColor] = colors;
console.log(thirdColor); // blue
3.3 结合扩展运算符
const [primary, ...others] = colors;
console.log(others); // ['green', 'blue']
四、混合解构技巧
4.1 对象与数组嵌套
const config = {
servers: [
{ ip: '192.168.1.1', port: 8080 },
{ ip: '192.168.1.2', port: 3000 }
]
};
const {
servers: [
{ ip: firstIP },
{ ip: secondIP }
]
} = config;
console.log(firstIP); // 192.168.1.1
4.2 函数参数解构
// 接收对象参数
function getUserInfo({ id, name, email = 'N/A' }) {
console.log(`ID: ${id}, Name: ${name}, Email: ${email}`);
}
getUserInfo({ id: 1, name: 'Alice' });
// 输出:ID: 1, Name: Alice, Email: N/A
五、解构赋值的高级用法
5.1 默认值设置
// 对象解构默认值
const { width = 100, height = 200 } = { width: 50 };
console.log(width); // 50
console.log(height); // 200
// 数组解构默认值
const [a = 1, b = 2] = [undefined, 5];
console.log(a); // 1
console.log(b); // 5
5.2 变量值交换
let m = 10;
let n = 20;
[m, n] = [n, m];
console.log(m, n); // 20 10
5.3 正则表达式匹配
const url = 'https://www.example.com:8080/path';
const regex = /^(https?):\/\/([^:/]+)(?::(\d+))?/;
const [, protocol, host, port = 80] = regex.exec(url);
console.log(protocol); // https
console.log(host); // www.example.com
console.log(port); // 8080
六、实际应用场景
6.1 API响应处理
// 典型API响应结构
const response = {
status: 200,
data: {
users: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
],
pagination: {
page: 1,
totalPages: 3
}
}
};
// 解构关键数据
const {
status,
data: {
users: [firstUser],
pagination: { page }
}
} = response;
console.log(status); // 200
console.log(firstUser); // { id: 1, name: 'Alice' }
6.2 React组件props接收
function UserCard({
name,
age,
avatar = 'default-avatar.png',
...otherProps
}) {
return (
<div {...otherProps}>
<img src={avatar} alt={name} />
<h3>{name}</h3>
<p>Age: {age}</p>
</div>
);
}
6.3 模块导入优化
// 传统导入方式
import React from 'react';
const { useState, useEffect } = React;
// 解构导入方式
import { useState, useEffect } from 'react';
七、注意事项
- 解构失败处理:
const { missingProp } = {}; // undefined
const [missingItem] = []; // undefined
- 不可迭代对象解构:
try {
const [a] = {}; // TypeError: {} is not iterable
} catch (e) {
console.error(e);
}
- 解构字符串:
const [a, b] = 'Hi';
console.log(a); // 'H'
console.log(b); // 'i'
- 解构null/undefined:
const { prop } = null; // TypeError
const [item] = undefined; // TypeError