const { profile: { image, bio } } = user;

这行代码可以分解为:

从 user 对象中提取 profile 属性

从 profile 对象中提取 image 和 bio 属性

将这两个属性值分别赋给同名的变量 image 和 bio

等价传统写法

// 传统写法
const profile = user.profile;
const image = profile.image;
const bio = profile.bio;

// 解构写法
const { profile: { image, bio } } = user;


####实际应用示例
示例1:基本使用

const user = {
  name: '张三',
  profile: {
    image: 'avatar.jpg',
    bio: '前端开发者',
    age: 28
  }
};

const { profile: { image, bio } } = user;

console.log(image); // 'avatar.jpg'
console.log(bio);   // '前端开发者'

示例2:重命名变量

const { profile: { image: userAvatar, bio: userBio } } = user;

console.log(userAvatar); // 'avatar.jpg'
console.log(userBio);    // '前端开发者'

示例3:默认值

const user = {
  profile: {
    image: 'avatar.jpg'
    // bio 属性缺失
  }
};

const { profile: { image, bio = '暂无简介' } } = user;

console.log(bio); // '暂无简介'


相关知识点
对象解构:const { prop } = obj

数组解构:const [first, second] = arr

混合解构:对象和数组解构可以混合使用

函数参数解构:

function showUser({ name, profile: { image } }) {
  console.log(`${name}的头像是${image}`);
}

最后修改:2025 年 05 月 05 日
如果觉得我的文章对你有用,请随意赞赏