解构赋值是JavaScript中从对象或数组按结构提取值并赋给变量的语法糖。对象解构依属性名匹配,可重命名、设默认值、嵌套解构;数组解构依索引顺序,支持跳过、剩余元素和交换变量;需注意null/undefined不可解构及类型兼容性问题。
JavaScript 解构赋值是一种语法糖,允许你从对象或数组中「按结构提取值」并直接赋给变量,而不是先取整个结构再手动取属性或索引。const { name, age } = user 这类写法就是解构,它不是创建新对象,而是读取已有结构的字段。
对象解构靠的是「属性名」,不是位置。左边的大括号 {} 中写的变量名,默认会去右边对象找同名属性:
const user = { name: 'Alice', age: 30, city: 'Beijing' };
const { name, age } = user;
// name → 'Alice', age → 30
常见陷阱和应对方式:
原属性名: 新变量名 语法:{ city: location }
undefined,不会报错{ role = 'user' },当 user.role 是 undefined 或不存在时生效{ profile: { avatar } },但注意 profile 本身必须存在,否则报 Cannot destructure property 'avatar' of 'undefined'
数组解构靠的是「位置」,左边方括号 [] 中的变量按顺序对应右边数组的索引:
const colors = ['red', 'green', 'blue']; const [first, , third] = colors; // first → 'red', third → 'blue'(中间用逗号跳过)
实用技巧:
[a, , c]
... 获取剩余项:[first, ...rest] → rest 是数组[a, b] = [b, a]
const [err, data] = await fetchJSON()(前提是函数返回数组)解构看着简单,但几个细节常导致运行时错误:
null 或 undefined 不能解构:对 let obj = null; const { x } = obj 会抛 TypeError: Cannot destructure property 'x' of 'null'
const { length } = 'abc' 是合法的(字符串有 length 属性),但 const { map } = 42 就会报错(数字没有 map)arguments、NodeList)也有效,但需确保它们有 Symbol.iterator 或是真实数组undefined 时触发,null 不算:function f({ x = 1 } = {}) {} 才能安全处理 null 入参真正要用好解构,关键不是记住语法,而是清楚每次操作背后访问的是什么值、它是否可枚举、是否存在、类型是否支持属性访问——这些比写法本身更容易出问题。