es6解构赋值
解构赋值语法是一个 Javascript 表达式,这使得可以将值从数组或属性从对象提取到不同的变量中。
数组解构赋值:
{ 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]; console.log(a,b,rest); //1 2 [ 3, 4, 5 ] }
{ let a,b; ({a,b}={a:1,b:2}) console.log(a,b); //1 2 }
{ let a,b,rest; [a,b,c=3]=[1,2]; console.log(a,b,c); //1 2 3 }
let a,b,rest; [a,b,c]=[1,2]; console.log(a,b,c); //1 2 undefined }
数组解构赋值的应用
//变量交换 { let a=1,b=2; [a,b]=[b,a]; console.log(a,b); //2 1 }
//分别取多个返回值很方便 { function f(){ return[1,2] } let a,b; [a,b]=f(); console.log(a,b); // 1 2 }
//选择性的接受需要的值 { function f(){ return[1,2,3,4,5] } let a,b; [a,,,b]=f(); console.log(a,b); // 1 4 }
//不知函数返回值的长度,只想取得想要的值 { function f(){ return[1,2,3,4,5] } let a,b; [a,...b]=f(); console.log(a,b); // 1 [2,3,4,5] }
{ function f(){ return[1,2,3,4,5] } let a,b; [a,,...b]=f(); console.log(a,b); // 1 [3,4,5] }
对象的解构赋值
{ let obj={ a:2, b:true } let {a,b}=obj; console.log(a,b); //2 true }
{ //对象 const people = { name: 'lux', age: 20 } const {age,name} = people //必须为name,age,即原属性名;其顺序可以改变,相应的值不变 console.log(`${name} --- ${age}`) // lux --- 20 }
{ let obj={ a:2, b:true } let {c,d}=obj; console.log(c,d); //undefined undefined }
{ let {a=3,b=5}={a:4} console.log(a,b); //4 5 } { let {a:c,b:d}={a:4,b:5} console.log(c,d); //4 5 }
对象解构赋值的应用
{ let metaData={ title:'abc', test:[{ title:'test', desc:'description' }] } let {title:esTitle,test:[{title:cnTitle}]}=metaData; //test:[{title:cnTitle}]必须和原来的形式一模一样 console.log(esTitle,cnTitle); //abc test }
//错误应用 { let metaData={ title:'abc', test:[{ title:'test', desc:'description' }] } let {title,test:[{titl}]}=metaData; console.log(title,test:[{titl}]); //报错test:[{titl}]) }
//可以是 { let metaData = { title: 'abc', test: [{ title: 'test', desc: 'description' }] } let { title: atitle, test: btitle } = metaData; console.log(btitle,atitle); //[{title: 'test', desc: 'description' }] 'abc' }