

新闻资讯
技术学院解构赋值是变量提取协议而非语法糖,按名(对象)或按序(数组)绑定值,不修改原结构;默认值仅对undefined生效,null/0/false/''不触发,需用??等兜底。
JavaScript 的 const { a, b } = obj 看似只是写法更短,实际它定义了一套「从复合结构中按名/按序提取值」的协议。它不改变原对象或数组,也不创建新结构,只做绑定——这意味着如果目标不存在,就会得到 undefined,而不是报错(除非你访问了 undefined.x)。
const { name, age } = user;,也可只赋值不声明(需加括号:({ x } = obj);)const { profile: { email } } = data;,一旦 profile 为 null 或 undefined,运行时直接报 Cannot destructure property 'email' of 'undefined'
很多人以为写 { name = 'anon' } = user 就能兜住所有情况,其实不然:默认值只在属性值为 undefined 时生效,对 null、0、false、'' 都不触发。
const user = { name: null, count: 0 };
const { name = 'guest', count = 1 } = user;
console.log(name); // null(不是 'guest')
console.log(count); // 0(不是 1)
要真正兜底,得手动判断或用空值合并操作符:
?? 预处理:const { name } = user; const
finalName = name ?? 'guest';
const { name: rawName } = user; const name = rawName || 'guest';(会把 0、false 也转成默认值)Cannot read property 'x' of undefined
数组解构支持用逗号占位跳过不需要的项,也支持 ...rest 收集剩余元素。这在处理函数返回值、CSV 行、API 响应时特别顺手。
const [first, , third, ...rest] = ['a', 'b', 'c', 'd', 'e']; console.log(first); // 'a' console.log(third); // 'c' console.log(rest); // ['d', 'e']
arr[0] 和 arr[2] 更具意图性,尤其当索引语义明确(如 [status, , message])...rest 必须是最后一个元素,否则报错:[a, ...middle, z] = arr ❌const [x] = []; → x 是 undefined;但若想确保有值,仍需后续校验把解构直接写进函数参数列表,比如 function connect({ host, port = 3000, timeout }) { ... },能让函数签名自文档化。但这也意味着调用方必须传入对象,且 key 名必须精确匹配。
TypeError: Cannot destructure property 'host' of 'undefined'
undefined(除非设了默认值)function connect({ host, port = 3000 } = {}) { ... }
function fn({ id }: { id: number }),不是 ({ id }: { id: number })
null 或字段名拼写错误。该加运行时校验的地方,不能因为写了 { name = 'x' } 就以为万事大吉。