对象解构:将对象的属性和方法快速批量赋值给一系列变量的简洁语法
- 对象属性的值将被赋值给与属性名相同的变量
- 注意解构的变量名尽量不要与外面的变量名冲突否则报错
- 对象中找不到与变量名一致的属性名时变量值为undefined
const { uname, age } = {
uname: '小小怪',
age: 18
}
console.log(uname)
console.log(age)
- 更改解构变量名,处理变量名冲突问题
//2.解构变量名改名 由于解构变量名与外部一个变量名相同 旧变量名:新变量名
const { uname: username, age: PeopleAge } = {
uname: '小小怪',
age: 18
}
- 多级对象解构
const pig = {
name: '佩奇',
family: {
mother: '猪妈妈',
father: '猪爸爸',
sister: '乔治'
},
age: 6
}
const { name, family: { mother, father, sister }, age } = pig
console.log(name, mother, father, sister, age)