JavaScript解构赋值是按模式从数组或对象中提取值并赋给变量的语法糖,基于位置顺序(数组)或属性名匹配(对象),支持跳过、默认值、剩余元素收集及重命名,但不深拷贝、不改变原结构,且对null/undefined解构会报错。
解构赋值是 JavaScript 中一种语法糖,允许你从数组或对象中「按模式提取值」并直接赋给变量,省去手动索引或属性访问的冗余写法。它不是深拷贝,也不改变原数据结构,只是读取和绑定。
数组解构基于「位置顺序」,左侧用方括号 [] 描述要取哪些位置的元素,支持跳过、默认值、剩余元素收集。
const [a, b] = [1, 2]; → a 得 1,b 得 2
const [first, , third] = ['a', 'b', 'c']; → first 是 'a',third 是 'c'
undefined 时生效,const [x = 10, y = 20] = [5]; → x 是 5,y 是 20
... 收集,const [head, ...tail] = [1, 2, 3, 4]; → tail 是 [2, 3, 4]
const colors = ['red', 'green', 'blue']; const [r, g, b] = colors; console.log(r); // 'red' console.log(g); // 'green'
对象解构基于「属性名匹配」,左侧用花括号 {} 列出要提取的键名;变量名默认与键同名,也可重命名或设默认值。
const { name, age } = { name: 'Alice', age: 30 };
const { title: bo
okTitle } = { title: 'JS Guide' }; → 变量叫 bookTitle,不是 title
const { user: { id, profile: { city } } } = { user: { id: 123, profile: { city: 'Beijing' } } };
undefined 时触发,null 或 0 不会触发:const { count = 1 } = { count: 0 }; → count 是 0,不是 1
const person = { name: 'Bob', role: 'developer', tags: ['js', 'react'] };
const { name, role, tags } = person;
console.log(name); // 'Bob'
console.log(tags); // ['js', 'react']
解构看着简单,但几个边界情况常导致运行时错误或意外行为。
undefined 或 null 解构会报错:const [a] = null; → TypeError: Cannot destructure property '0' of 'null' as it is null.
function fn({ x = 0 } = {}) { ... }
const { [key]: val } = obj;(这是计算属性,属于对象字面量定义语法,不是解构)for...of 配合数组解构很自然,但 for...in 遍历对象键名时不能直接解构值最常被忽略的是:解构只是语法便利,背后仍依赖原始值的可迭代性或属性可访问性;别把它当成万能取值工具,尤其处理不确定结构的数据时,先做存在性检查更稳妥。