數(shù)組的解構(gòu)賦值:
let [a,b,c]=[1,2,3]; ==>let a=1;let b=2;let c=3;
let [head,...tail]=[1,2,3,4]; ==> head = 1 , tail = [2,3,4]
let [x,y,...z]=['a']; ==> x = "a" y=undefined z=[]
分析:因為解構(gòu)賦值是依次對應(yīng)的昂儒,x對應(yīng)"a"资昧,y沒有對應(yīng)值,為undefined荆忍,...z表示剩余內(nèi)容格带,剩余為空,因此為空數(shù)組[]
let [a,[b],d]=[1,[2,3],4]; a==>1,b==>2,d==>4
分析:a和d不必哆嗦刹枉,[b]=[2,3],解構(gòu)賦值,b=2叽唱;3沒有對應(yīng)值,忽略
...運(yùn)算符兩種用法:
展開運(yùn)算符(用在array和object上):let a = [1,2,3]; let b = [0,...a,4]; ==>[0,1,2,3,4]
剩余操作符(結(jié)構(gòu)的一種微宝,一般只針對array)棺亭,舉例就是上面的。解構(gòu)不成功蟋软,變量的值就是undefined镶摘。如果等號右邊不是數(shù)組或不可遍歷,會報錯岳守。比如:
let [foo]=1; let [foo]=false; let [foo]=NaN; let [foo]=undefined; let [foo]=null; let [foo]={};這些等號右邊的值都不可遍歷凄敢,因此都會報錯
解構(gòu)允許賦默認(rèn)值: let [x,y = 'b']=['a',undefined]; x==>'a',y==>'b'
如果數(shù)組成員不嚴(yán)格為undefined,默認(rèn)值不會生效:let [x,y = 'b']=['a',null]; x==>'a',y==>null
對象的解構(gòu)賦值:
對象的解構(gòu)賦值是按名稱對應(yīng)來的湿痢,名稱不對應(yīng)值就為undefined涝缝。而數(shù)組是按次序排列的
let [bar,foo]={foo:"aaa",bar:"bbb"}; ==>foo:aaa,bar:bbb
對象的解構(gòu)賦值是下面形式的簡寫:let {foo:foo,bar:bar}={foo:'aaa',bar:'bbb'}
var {foo:baz}={foo:'aaa',bar:'bbb'}; ==>baz:aaa
foo稱為模式,baz稱為變量
let {foo:baz}={foo:'aaa',bar:'bbb'}; ==>baz:aaa,foo:foo is not defined
對象的解構(gòu)也可以賦默認(rèn)值:var {x:y=3}={x:5}; ==> y:5
默認(rèn)值生效的條件也是對象的屬性值嚴(yán)格等于undefined
已經(jīng)聲明的變量不能用于解構(gòu)賦值:let x; {x}={x:1}; ==>報錯譬重。因為這里JavaScript引擎會將{x}解析為代碼塊拒逮,通過({x}={x:1}); 則能正確解析
解構(gòu)賦值左邊可以不放任何東西
字符串也可以解構(gòu)賦值,類似數(shù)組的對象都有l(wèi)ength屬性臀规,也可以對其解構(gòu)賦值:let {length:len}='hello'; ==> len:5
解構(gòu)賦值時滩援,如果等號右邊是數(shù)值和布爾值,則會先轉(zhuǎn)為對象
let {prop:x}=undefined; ==>TypeError undefined和Null不能轉(zhuǎn)化為對象
let {prop:x}=null; ==>TypeError
注意:模式不能使用圓括號
解構(gòu)賦值的用途
交換變量的值:let x=1; let y=2; [x,y]=[y,x];
從函數(shù)返回多個值:
function example(){
return [1,2,3];
}
let [a,b,c]=example(); //返回數(shù)組
function example(){
return {foo:1,bar:2};
}
let {foo,bar}=example(); //返回對象
- 函數(shù)參數(shù)的定義:
functoin f([x,y,z]){
...
}
f([1,2,3]); //有次序的參數(shù)
function f({x,y,z}){
...
}
f({z:3,y:2,x:1}); //無次序的參數(shù)
- 提取json數(shù)據(jù):
let jsonData={
id:42,
status:"ok",
data:[132,456]
};
let {id,status,data}=jsonData;
- 函數(shù)參數(shù)的默認(rèn)值:
jQuery.ajax=function(url,{
async=true,
beforeSend=function(){},
cache=true}){...}
- 遍歷Map結(jié)構(gòu):
var map=new Map();
map.set('first','hello');
map.set('second','world');
for (let [key,value] of map){
console.log(key,value)
}
for (let [key] of map){
console.log(key)
}
for (let [,value] of map){
console.log(key)
}
- 輸入模塊的指定方法:
const { SourceMapConsumer, SourceNode } = require("source-map");
最后注意一點(diǎn):解構(gòu)賦值的參數(shù)必須在最右邊
例如:
const [a,...b]=[1,2,3,4]能正確解構(gòu)塔嬉,而const [...a,b]=[1,2,3,4]會報錯玩徊,如果是三個參數(shù),const [a,...b,...c]=[1,2,3,4]也是錯誤的