const person = {
name = "zhangsan"
age:12,
city:"西安"
}
有对象person ,要获取里面的值,原来的方式是:
const name = person.name
const age = person.age
const city = person.city
这样获取值是很麻烦的,如果用解构的话怎么做:
const {name,age,city} = person
获取对象的值 用 {} 如果是数组的话就是 [ ]
稍微复杂一点的结构
const person ={
name:"zhangsna"
age:12,
city:"西安"
social:{
qq:"11111"
weixin:"dfsdf"
}
}
// 获取 qq 和 weixin
const {qq,weixin} = person.social
//获取name 和 qq
const {name,social:{qq} } = person
获取数据的时候给他重命名
const { name: personName, social:{qq:qqNumer}} = person
赋值的变量在object不存在的情况
// 防止获取的对象值不存在的情况,给它一个默认值,没找到的话就显示默认值
const { name: personName="guest", social:{qq:qqNumer}} = person
数组的解构赋值把{} 换成 [] 就可以了
// 对字符串的处理
const info = "zhangsn, 12 , sffds";
const person = info.split(",");
const [name,age,text] = person;
数组解构常用功能,互换两个变量的值
//交换两个值
let a = 1
let b = -1
//老方法
let temp = a;
a=b;
b=temp;
//解构
[a,b] = [b,a]
实际使用示例
// 解构赋值获得产品名 价格 和 产品重量
const product = {
name:'water',
price:2.2,
dimen:{
weight:2,
height:20
}
}
{name,price,dimen:{weight}} = product
// 得到一个字符串,处理字符串,通过字符串获取 产品名,价格,和生产日期
const record = "water,2,Oct 11 2020";
const arr = record.split(',')
{name,price,date} = arr
// 互换 两个值
let width = 100
let height = 200
[width,height] = [height,width]