深入理解ES6之解構(gòu)

一:為什么用解構(gòu):

在之前提取數(shù)據(jù)對象需要逐個賦值,可能會為了一個小數(shù)據(jù)挖掘整個機構(gòu),ES6給數(shù)組和對象添加了解構(gòu)可以方便提取數(shù)據(jù)。

二:對象解構(gòu):

1:

let node = {
    type:"node",
    name:"haha",
 }
 let {type,name} = node;
 console.log(type)//"node"
 console.log(name)//"haha"

注意:當(dāng)解構(gòu)賦值表達式的右側(cè)(等號右邊)的計算結(jié)果為null或者undefined時,會報出異常。因為任何讀取nul或者undefined的斗湖導(dǎo)致運行時錯誤。
2:默認值

let {type,name,value} = node;
 console.log(type)     //"node"
 console.log(name)   //"haha"
console.log(value)    //undefined
let {type,name,value="vvvv"} = node;
console.log(value)    //"vvvv"

3:賦值給不同的本地變量名

let node = {
    type:"node",
    name:"haha",
 }
let {type:localtype,name:localname="wuyunqiang"} = node;
console.log(localtype);       //"node"
console.log(localname);     //"haha"

4:嵌套的推向解構(gòu)

let node = {
     type:"id",
     name:"haha",
       loc:{
         start:{
            line:1,
            column:1
         },
         end:{
           line:1,
           column:4
         },
      }
}
let {loc:{start}} = node;
console.log(start.line)
console.log(start.column)

三:數(shù)組解構(gòu):

數(shù)組解構(gòu)和對象解構(gòu)比較相似,對象是根據(jù)key來檢索取值,數(shù)組是根據(jù)位置來檢索取值。
1:根據(jù)位置索引賦值

let colors = ["red","green","blue"];
let [ , second] = colors;
console.log(second)//"green"

2:用于值交換

ES6 之前
let a = 1 ;
let b = 2;
let tmp;
tmp =a; a= b;b= tmp;
console.log(a)//2
console.log(b)//1

ES6之后
let a = 1; let b = 2;
[a,b] = [b,a];
console.log(a)//2
console.log(b)//1

3:默認值嵌套索引類似于對象
4:剩余項

let colors = ["red","green","blue"];
let [first ,...rest] = colors;
console.log(first);             // "red"
console.log(rest.length)   // 2
console.log(rest[0])          //"green"

四:混合解構(gòu):

對象與數(shù)組解構(gòu)能被用到一起。

let node = {
     type:"id",
     name:"haha",
       loc:{
         start:{
            line:1,
            column:1
         },
         end:{
           line:1,
           column:4
         },
      }
   range:[0,3]
}
let {loc :{start},range:[startindex]}=node;
console.log(start.line); // 1
console.log(startindex) // 0

混合使用對象與數(shù)組解構(gòu),node的任何部分都能提取出來。對于從JSON配置結(jié)構(gòu)中抽取數(shù)據(jù)來說,這種方法尤為有用,因為他不需要探索整個結(jié)構(gòu)。

五:參數(shù)解構(gòu):

參數(shù)結(jié)構(gòu)提供了更清晰地標(biāo)明函數(shù)期望輸入的替代方案。它使用對象或數(shù)組的模式替代了具名參數(shù)。

function setCookie(name,value,{secure,path,domain,expires}){//設(shè)置cookie的代碼}
setCookie("type","xxx",{secure:true,expires:20000})

注意
1:結(jié)構(gòu)的參數(shù)是必須的,否則會報錯
2:參數(shù)結(jié)構(gòu)也可以設(shè)置默認值

function setCookie(name,value,{
    secure=true,
    path="xxxx",
    domain="xxxx",
    expires=20000
}={}){//設(shè)置cookie的代碼}
setCookie("type","xxx",{secure:true,expires:20000})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容