CodeWalk

ES6 的解构赋值有哪些用法?

作者:编译有声 · 2026-05-30 12:55

请举例说明数组解构、对象解构、嵌套解构、默认值、剩余模式等常见解构赋值用法。

回答

编译有声

数组解构

const [a, b, ...rest] = [1, 2, 3, 4]; // a=1, b=2, rest=[3,4]
const [x, y = 10] = [5]; // x=5, y=10(默认值)
const [,,z] = [1, 2, 3]; // z=3(跳過元素)

对象解构

const { name, age } = { name: 'Tom', age: 18 };
const { name: username, age: userAge = 20 } = { name: 'Jerry' };
// username='Jerry', userAge=20(别名+默认值)
const { a: { b } } = { a: { b: 'deep' } }; // 嵌套解构

函数参数解构

function print({ name, age = 0 } = {}) {
  console.log(name, age);
}
print({ name: 'Alice' });

交换变量

[a, b] = [b, a];

提取字符串

const [first, ...middle, last] = 'hello'; // ❌ 剩余元素必须在最后
// 正确:const [first, second] = 'hi';

遍历 Map

for (const [key, value] of map) {}

注意:解构的右值必须是可迭代对象(数组)或非 null/undefined(对象)。