讲解

解构赋值把「从数组或对象里取值」从多行代码压缩成一个模式匹配表达式。数组解构按位置取:const [a, b] = [1, 2];对象解构按键名取:const { name, age } = user。两种都支持默认值(const { page = 1 } = options,只在值为 undefined 时生效)、跳过元素(const [, second] = arr)、嵌套解构(const { address: { city } } = user)。

对象解构还有几个高频变体:重命名 const { name: userName } = user 把 name 属性的值放进新变量 userName;配合剩余语法 const { id, ...rest } = obj 把除 id 外的属性收进新对象 rest(浅拷贝的常用技巧);交换两个变量不再需要临时变量:[a, b] = [b, a]。函数参数位置用解构尤其强大:function render({ title, items = [] }) 让调用方传一个配置对象,参数有名字、有默认值、顺序无关,这是现代 JavaScript 函数签名的主流写法。

需要注意的边界:对已声明变量做对象解构赋值要用括号包住整行(({ a } = obj)),否则花括号被当成代码块;解构 null/undefined 会抛 TypeError(const { x } = null 直接炸),来源可能为空时给整个模式加默认值 const { x } = maybeNull ?? {}。

示例

// 数组解构:按位置
const rgb = [255, 128, 0];
const [r, g, b] = rgb;
console.log('RGB:', r, g, b);

// 跳过元素 + 默认值
const [, second, , fourth = 40] = [10, 20, 30];
console.log(second, fourth);

// 交换变量
let m = 1;
let n = 2;
[m, n] = [n, m];
console.log('交换后:', m, n);

// 对象解构:按键名
const user = { name: '小明', age: 18, city: '北京' };
const { name, age } = user;
console.log(name, age);

// 重命名 + 默认值 + 剩余
const { name: userName, role = '访客', ...others } = user;
console.log(userName, role, others);

// 函数参数解构:命名参数
function formatPrice({ amount, currency = '¥', digits = 2 }) {
  return currency + amount.toFixed(digits);
}
console.log(formatPrice({ amount: 19.9 }));
console.log(formatPrice({ amount: 8, currency: '$', digits: 0 }));

// 嵌套解构
const resp = { data: { list: [1, 2, 3], total: 3 } };
const {
  data: { total },
} = resp;
console.log('总数:', total);

常见坑

  • 解构 null/undefined:const { a } = undefined 抛 TypeError。来源可能为空时用 ?? {} 兜底。
  • 默认值只对 undefined 生效:{ page = 1 } 中传入 null 时 page 是 null,不会变 1。接口数据常带 null,要特别小心。
  • 已声明变量的对象解构赋值:a = { b: 1 } 模式的 ({ b } = a) 必须加外层括号,否则语法错误。
  • 数组解构深坑:const [a] = null 同样抛错;而 const [a] = [] 得到 undefined 不报错——数组解构对「可迭代但空」宽容,对 null 不宽容。

小结

数组按位置、对象按键名解构,支持默认值、重命名、剩余收集;函数参数解构实现命名参数。下一节看与解构一体两面的展开/剩余语法。