一、解构赋值 快速地从复杂结构中提取我要的内容
1. 简单对象的解构
<script>
const obj = {
name: "胡莎",
age: 18,
gender: "女",
isRich: true
};
/* 解构赋值 */
// let {name} = obj
// let {age} = obj
// let {gender} = obj
// let {isRich} = obj
// console.log(name,age,gender,isRich); //胡莎 18 女 true
/* 一次性解构出多个变量 */
let {name,age,gender,isRich} = obj
console.log(name,age,gender,isRich); //胡莎 18 女 true
</script>
2. 多级结构的对象
<script>
const obj = {
name: "胡莎",
age: 18,
family: {
name: "胡腾飞",
age: 54
},
family2: {
name: "李琴",
age: 53
}
};
// let { name, age, family, family2 } = obj
// console.log(name, age, family, family2);
/* 只解构(deconstruct)其中的一部分内容 */
// let { name, family: { age }, family2: { age: age2 } } = obj
// console.log(name, age, age2); //胡莎 54 53
/* 解构的同时取别名 */
let { name: n, family: { age: a } } = obj
// console.log(name, age); //age is not defined
console.log(n, a); //胡莎 54
</script>