JavaScript es6 解構賦值

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]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章