1.一般解构
const person = { name: "yaya", age: 18, city:"郑州" } // 当从对象中解构时用{}。从数组中解构时用[] // {属性名1,属性名2...} = 从哪里结构 const {name, age, city} = person console.log(name, age, city) //yaya 18 郑州
2.当要解构 的属性在对象中的对象中时,一定要手动到属性所在的外层
// 对象嵌套 const person2 = { name: "yaya", age: 18, city:"郑州", social:{ weibo:"yatingFeng", bokeyuan:"yaya003" } } const {weibo,bokeyuan} = person2.social console.log(weibo,bokeyuan) //yatingFeng yaya003
3.同时解构对象中的属性和对象中的对象中的属性
const person2 = { name: "yaya", age: 18, city:"郑州", social:{ weibo:"yatingFeng", bokeyuan:"yaya003" } } const {name,social:{bokeyuan}} = person2 console.log(name,bokeyuan) //yaya yaya003
4.解构的同时重命名
const person2 = { name: "yaya", age: 18, city:"郑州", social:{ weibo:"yatingFeng", bokeyuan:"yaya003" } } const {name:myName,social:{bokeyuan:boke}} = person2 console.log(myName,boke) //yaya yaya003
5.当解构的属性不存在时:为undefined,
当设置默认值:若属性不存在时,返回默认值;属性存在时,返回属性对应的值
const person2 = { // name: "yaya", age: 18, city:"郑州", social:{ weibo:"yatingFeng", bokeyuan:"yaya003" } } const {name:myName="牙牙",social:{bokeyuan:boke}} = person2 console.log(myName,boke) //牙牙 yaya003
数组的用法与对象相同,只是将{}换为[]
数组的应用场景:一般拿到的是一个字符串,将这个字符串分割成数组,在从数组中解构赋值
const info = "亚婷,18,0366" const infoArr = info.split(',') //["亚婷", "18", "0366"] const [name, age, id] = infoArr console.log(name, age, id) //亚婷 18 0366
这里特别提出,用数组互换两个变量的值比较常用
之前互换两个值一般引用中间变量temp
这里可以很方便的解决:
let a = 1; let b = -1; [a, b] = [b, a]; console.log(a,b) //-1 1