前言:
ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构
一、数组的解构赋值
1.格式:let [a,b,c] = [1,2,3]
es6之前的赋值
{ var arr = [1,2,3]; var a,b,c; a = arr[0]; b = arr[b]; c = arr[c]; }
es6的赋值
{ let arr = [1,2,3]; let [a,b,c] = arr; console.info(a,b,c);//1 2 3 }2. 注意:
1).如果匹配不到,则变量值是undefined
{ let [a,b,c] = [1,2]; console.info(a,b,c);//1 2 undefined } { const [a,b,c] = [1,2]; console.info(a,b,c);//1 2 undefined }
2)如果等号的右边不是数组(或者严格地说,不是可遍历的结构),那么将会报错
//要求是可iterator的数、并且左右两边的数据类型要一致,比如都是数组或者都是对象 { let [num] = { num:1, str:"2" }; console.info(num);//报错 }
3.默认值(当要赋值的值严格等于undefined时,默认值生效)
{ let [a=true] = []; console.info(a);//true let [b=true] = [undefined]; console.info(b);//true let [c=true] = [null]; console.info(c);//null let [d=true] = [1]; console.info(d);//1 }
4.rest(...)
/*...相当于余下的所有值组成的数组*/ { let [a,b,...c] = [1,2,3,4,5,7,7] console.info(a,b,c);//1 2 (5) [3, 4, 5, 7, 7] c.push("aaa"); console.info(c);//(6) [3, 4, 5, 7, 7, "aaa"] }
5.实战
{ // 交换变量 let a=1; let b=2; [a,b]=[b,a] console.log(a,b);// 2 1 }
二、对象的解构赋值
1.格式:let {a,b,c} = {a:1,b:2,c:3} 是通过key来匹配的,而不是根据顺序
对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量
{ let {a,b} = {a:1,b:2}; console.info(a,b);//1 2 } { let {a,b} = {aaa:3,b:4}; console.info(a,b);// undefined 4 }{ let {a,b} = {b:4,a:3}; console.info(a,b);//3 4 }{ let {foo:a} = {foo:'aaa'}; //console.info(foo);//foo是模式,报ReferenceError console.info(a);//aaa }
2.嵌套结构的赋值
{ let obj = { p:[ 'hello', {y:"world"} ] } let {p:[x,{y}]} = obj; console.info(x,y);//hello world }
3.默认值(默认值生效的条件是,对象的属性值严格等于undefined)
{ let {a=true} = {a:1}; console.log(a);//1 } { let {a=true} = {a:undefined}; console.log(a);//true } { let {a=true} = {a:null}; console.log(a);//null }
三、字符串解构赋值
1.格式:let [a,b,c] = '123' 字符串被转换成了一个类似数组的对象
{ let [a,b] = 'hello'; console.info(a,b);// h 3 } { let [a,b,c] = 'h2'; console.info(a,b,c);//h 2 undefined }
2.带有的length,toString等属性
{ let {length:len} = "hello"; console.info(len);//5 } { let {toString:a} = 12; console.info(a);//ƒ toString() { [native code] } console.info(a===Number.prototype.toString);//true }
四、函数解构赋值
{ function fn([a,b]){ return a+b; } console.log(fn([3,1]));//4 } { function fn(){ return [1,2] } let a,b; [a,b] = fn(); console.info(a,b);//1 2 } { function fn(){ return [1,2,3,4,5,6,7] } //let a,b,c; let [a,,,b,...c] = fn(); console.info(a,b,c);//1 4 (3) [5, 6, 7] }