這種寫法屬于“模式匹配”虽抄,只要等號兩邊的模式相同脸侥,左邊的變量就會(huì)被賦予對應(yīng)的值畏纲。下面是一些使用嵌套數(shù)組進(jìn)行解構(gòu)的例子扇住。
如果解構(gòu)不成功,變量的值就等于undefined盗胀。
let[foo,[[bar],baz]]=[1,[[2],3]];
運(yùn)行結(jié)果:
? ? ? ? ? ? ? ? ?foo //1
? ? ? ? ? ? ? ? ?bar //2
? ? ? ? ? ? ? ? ?baz// 3
?let ?[,,third]=["foo","bar","baz"];
運(yùn)行結(jié)果:
? ? ? ? ?third // "baz"艘蹋;
?let[x,,y]=[1,2,3];
?運(yùn)行結(jié)果:
? ? ? ? ? x//?1;
? ? ? ? ? ?y// 3;
?let[head,...tail]=[1,2,3,4];
? 運(yùn)行結(jié)果:
? ? ? ? ? ? ? ? ? ? ?head // 1;
? ? ? ? ? ? ? ? ? ? ?tail // [2, 3, 4];
let[x,y,...z]=['a'];
運(yùn)行結(jié)果:
? ? ? ? ? ? ? ? ? ? x // "a";
? ? ? ? ? ? ? ? ? ? ?y // undefined;
? ? ? ? ? ? ? ? ? ? ?z // [];