结构赋值即按照一种模式对变量进行赋值,分为数组解构赋值和对象结构赋值
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