{let a, b, rest;[a,b]=[1,2];
console.log(a,b);//1,2}{let a, b, rest;[a,b,...rest]=[1,2,3,4,5,6];
console.log(a,b,rest);//1,2,[3,4,5,6]//注意rest現在是一個數組//是數組解構賦值的一個特性}{let a, b
{a,b}={a:1, b:2}
console.log(a,b)//1,2}//其他類型的解構賦值都是在數組解構賦值和對象解構賦值上的延伸
數組解構賦值&對象解構賦值
使用方法
默認值
使用場景
數組解構賦值——使用場景
默認值使用場景
{let a, b, c
[a,b,c=3]=[1,2];
console.log(a,b,c)//1,2,3}{let a, b, c
[a,b,c]=[1,2];
console.log(a,b,c)//1,2,undefined//*如果解構賦值在結構上沒有配對,也就是說,c只聲明沒賦值,那就是undefined,所以默認值就是解決這個問題的*}//用於變量交換{let a =1;let b =2;[a,b]=[b,a];
console.log(a,b);//2,1}//{functionf1(){return[1,2];}let a, b;[a,b]=f1();//1,2}//在返回值中選擇性的接收多個變量{functionf2(){return[1,2,3,4,5];}let a, b, c;[a,,,b]=f2()
console.log(a,b)//1,4}//返回值的長度未知,只關心第一個,其餘的返回一個數組,後面需要時候,再遍歷數組,這與上面這個場景可以混合使用{functionf3(){return[1,2,3,4,5];}let a, b, c;[a,...b]=f3()
console.log(a,b)//1,[2,3,4,5]let e, f;[e,,...f]=fn3()
console.log(e,f)//1,[3,4,5]}