結構賦值即按照一種模式對變數進行賦值,分為數組解構賦值和對象結構賦值 1. 數組結構賦值 let a; [a,b]=[1,2]//數組類型解構賦值 console.log(a);//1 [a,b,...rest]=[1,2,3,4,5,6]//輸出1,2,[3,4,5,6] [a,b,c=3]=[1 ...
結構賦值即按照一種模式對變數進行賦值,分為數組解構賦值和對象結構賦值
1. 數組結構賦值
let a; [a,b]=[1,2]//數組類型解構賦值 console.log(a);//1 [a,b,...rest]=[1,2,3,4,5,6]//輸出1,2,[3,4,5,6] [a,b,c=3]=[1,2] //a=1,b=2,c=3 [a,b,c]=[1,2]//若左右沒有配對成功,則會輸出undefined。即c為undefined let a=1; let b=2; [a,b]=[b,a];//可以進行交換,輸出2,1 function f(){ return [1,2] } let a,b; [a,b]=f();//輸出1,2 function f(){ return [1,2,3,4,5] } let a,b,c; [a,,,b]=f();//a,b輸出1,4 function f(){ return [1,2,3,4,5] } let a,b,c; [a,...b]=f();//a,b輸出1,[2,3,4,5]
2.對象解構賦值
let o={p:42,q:true} let {p,q}=o;//對象解構賦值左右都是對象 console.log(p,q);//42,true let {a=10,b=5}={a:3}; console.log(a,b);//3,5 let metaData={ title:"abc", test:[{ title:"test", desc:"description" }] } let {title:esTitle,test:[{title:cnTitle}]}=metaData; console.log(esTitle,cnTitle);//輸出abc,test