解构赋值中属性名与变量名不一致时用冒号重命名,如{ name: userName };支持嵌套重命名与默认值;需防null/undefined报错,可配合默认值={};剩余属性...rest须居末;函数参数解构需设默认空对象防错。

解构赋值时属性名和变量名不一致怎么办
直接用 const { name: userName } = user,冒号左边是对象里的属性名,右边是你要声明的变量名。这在 API 返回字段名不友好(比如 user_name、created_at)时特别实用。
常见错误是写成 { userName: name }——顺序反了,JS 会去对象里找叫 userName 的属性,找不到就得到 undefined。
- 支持嵌套重命名:
{ profile: { avatar: avatarUrl } } - 可同时默认值:
{ id, name: userName = 'anonymous' } - 别对
null或undefined解构,会报TypeError: Cannot destructure property ... of 'undefined'
从嵌套对象里一层层取值要写很多点?
用嵌套解构,避免 data?.user?.profile?.avatar 这种冗长写法。只要路径存在,就能一次性提取最深层字段。
const { user: { profile: { avatar, bio } } } = response;
但要注意:如果中间某一层是 undefined(比如 response.user 不存在),整个解构就会失败。稳妥做法是配合默认值:
立即学习“Java免费学习笔记(深入)”;
const { user = {} } = response;
const { profile = {} } = user;
const { avatar, bio } = profile;
或者一步写全(更紧凑):
const { user: { profile: { avatar, bio } = {} } = {} } = response;
这个写法看着绕,但意思是:如果 user 不存在,用空对象代替;如果 profile 不存在,也用空对象代替——从而避免报错。
想取完一部分属性,再把剩下的收进一个新对象?
用剩余属性语法 ...,它必须是解构模式里的最后一个元素。
const { id, name, ...rest } = user;
rest 会包含 user 对象里除 id 和 name 外的所有其他自有属性(不含原型链上的)。
- 不能写成
{ ...rest, id, name },语法错误 -
rest不会包含不可枚举属性或 symbol 键 - 如果原对象有 getter,
rest里对应的是 getter 的返回值,不是 getter 函数本身
函数参数直接解构是不是更简洁?
是,尤其适合配置类函数。把选项对象的结构直接写在参数位置,语义清晰,还能设默认值。
function connect({ host = 'localhost', port = 3000, timeout = 5000 }) {
console.log(`Connecting to ${host}:${port} (timeout: ${timeout}ms)`);
}
调用时传一个对象就行:connect({ host: 'api.example.com', timeout: 10000 })。
容易踩的坑:
- 不能省略传参,哪怕传空对象
{},否则Cannot destructure property ... of 'undefined' - 如果想支持无参调用,得给整个参数设默认值:
function connect(opts = {}) { ... } - TypeScript 用户注意:解构参数的类型需显式标注,否则推导可能不准确











