JS 解构赋值深入
学习解构 · 难度:进阶 · +15XP
JS 解构赋值深入
JavaScript 解构赋值深入 — 从数组和对象中提取数据
学习前的准备
打开浏览器控制台(F12)。你需要了解数组和对象的基本操作。解构赋值是 ES6 带来的一大语法革新。
回顾数组解构
const nums = [10, 20, 30, 40, 50];
const [a, b, c] = nums;
console.log(a, b, c); // 10 20 30
const [first, , third] = nums;
console.log(first, third); // 10 30
const [head, ...tail] = nums;
console.log(tail); // [20, 30, 40, 50]
const [x = 1, y = 2, z = 3] = [100];
console.log(x, y, z); // 100 2 3
深入对象解构
const product = {
id: 10001, name: '机械键盘', price: 299,
specs: { brand: '某品牌', layout: '87键' },
tags: ['办公', '游戏']
};
const { name, price } = product;
const { name: title, stock = 0 } = product;
const { specs: { brand, layout } } = product;
const { tags: [primaryTag] } = product;
console.log(primaryTag); // '办公'
函数参数解构
function createOrder({ item, qty = 1, discount = 0 }) {
console.log('商品:' + item + ',数量:' + qty);
}
createOrder({ item: '笔记本', qty: 3 });
// 参数顺序不重要!
常见使用场景
// 交换变量
let m = 1, n = 2; [m, n] = [n, m];
// 从函数返回多个值
function getMinMax(arr) { return [Math.min(...arr), Math.max(...arr)]; }
const [min, max] = getMinMax([3, 1, 4, 1, 5, 9]);
// 提取 JSON 数据
const { data: { user, token } } = response;
小结
解构赋值让数据提取变得简单优雅。数组解构按位置,对象解构按属性名。在函数参数中使用解构是最佳实践——它让参数含义自文档化。在实际开发中,解构是处理 API 返回数据时不可或缺的工具。