解构赋值中属性名与变量名不一致时用冒号重命名,如{ 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 不存在),整个解构就会失败。稳妥做法是配合默认值:
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 键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 = {}) { ... }