一:為什么用解構(gòu):
在之前提取數(shù)據(jù)對象需要逐個賦值爹耗,可能會為了一個小數(shù)據(jù)挖掘整個機(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)賦值表達(dá)式的右側(cè)(等號右邊)的計算結(jié)果為null或者undefined時,會報出異常潭兽。因?yàn)槿魏巫x取nul或者undefined的斗湖導(dǎo)致運(yùn)行時錯誤。
2:默認(rèn)值
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:默認(rèn)值嵌套索引類似于對象
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ù)來說,這種方法尤為有用藻懒,因?yàn)樗恍枰剿髡麄€結(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è)置默認(rèn)值
function setCookie(name,value,{
secure=true,
path="xxxx",
domain="xxxx",
expires=20000
}={}){//設(shè)置cookie的代碼}
setCookie("type","xxx",{secure:true,expires:20000})