①对象解构是将对象的属性和方法快速批量赋值给一系列变量的简洁语法
<script>
const obj = {
uname: '张三',
age: 20
}
// const {} = obj
// const {} = {uname: '张三', age: 20}
const {uname, age} = {uname: '张三', age: 20}
//变量名与对象的属性名必须一致,且外面没有和uname、age相同的变量名
// 若对象中找不到与变量名一致的属性名变量值返回为undefined
// 等价于const uname = obj.uname
console.log(uname) //张三
console.log(age) //20
</script>
②变量名有冲突时可更改变量名
<script>
const obj = {
uname: '张三',
age: 20
}
// 万一外面有与声明的变量名一模一样的名字的变量名,可以更改声明的变量名
// 语法 旧变量名:新变量名
const {uname:uname1, age:age1} = {uname: '张三', age: 20}
// 打印时打印新的变量名
console.log(uname1) //张三
console.log(age1) //20
</script>
③数组对象解构
<script>
const obj = [
{
uname: '张三',
age: 20
}
]
const [{uname, age}] = [{uname: '张三', age: 20} ]
console.log(uname) //张三
console.log(age) //20
</script>
④多级对象解构
<script>
const pig = {
uname: '佩奇',
family:{
mother: '猪妈妈',
father: '猪爸爸',
son: '乔治'
},
age: 6
}
// 多级数组解构
// const {} = pig
const {uname, family:{mother, father, son}, age} = pig
console.log(uname) // 佩奇
console.log(mother) // 猪爸爸
console.log(father) // 猪妈妈
console.log(son) // 乔治
console.log(age) // 6
</script>