1、什么是解构赋值
ES6允许按照预定的模式,从数组、对象中提取值,对变量进行赋值。
我们直接用例子说明。
2. 数组的解构赋值
数组传统的变量赋值:
var arr=[1,2,3];
var a=arr[0];
var b=arr[1];
var c=arr[2];
console.log(a); //1
console.log(b); //2
console.log(c); //3
数组的解构赋值:
var arr[a,b,c]=[1,2,3];
console.log(a); //1
console.log(b); //2
console.log(c); //3
数组解构赋值的几种情况:
(1)数值中嵌套数组
var arr[a,b, [c,d]]=[1,2,[3,4]];
console.log(a); //1
console.log(b); //2
console.log(c); //3
console.log(4); //4
(2) 不完成解构
var arr[a,b, c]=[1,2];
console.log(a); //1
console.log(b); //2
console.log(c); //undefined
(3) 设置默认值
var arr[a,b, c=3]=[1,2];
console.log(a); //1
console.log(b); //2
console.log(c); //3
(4) 修改默认值
var arr[a,b, c=3]=[1,2,4];
console.log(a); //1
console.log(b); //2
console.log(c); //4
2. 对象的解构赋值
var {a,b,c}={"a":1,"b":2,"c":3};
console.log(a); //1
console.log(b); //2
console.log(c); //3
与数组的解构赋值不同之处:数组中按顺序赋值,而对象是按属性名赋值。例:
var {a,b,c,d}={"a":1,"c":2,"b":3,"e":4};
console.log(a); //1
console.log(b); //3
console.log(b); //2
console.log(d); //undefined
这时,我们可以做出修改,使d取得e的赋值: var {a,b,c,d:e}={"a":1,"c":2,"b":3,"e":4}; (将e赋值给d)
(1)对象的嵌套赋值
var {a:{b}}={"a":{"b":1}}
console.log(a); //报错
console.log(b); //1
(2)指定默认值
var {a,b=2}={"a":1}
console.log(a); //1
console.log(b); //2
(3)字符串的解构赋值
var {a,b}='你好';
console.log(a); //你
console.log(b); //好
3. 解构赋值的作用
(1)交换数值:不必引入中间的临时变量
var x=1;
var y=2;
[x,y]=[y,x];
(2)提取函数返回的多个值:(函数只能有一个返回值,将多个值放在数组或对象中返回)
function demo(){
return {"name":"a","age":"15"};
}
var {name,age}=demo();
console.log(name); //a
console.log(age); //15
(3)定义函数参数:(只获取需要的参数,忽略多余的参数)
function demo(a,b){
console.log("name:"+a); //name:haha
console.log("age:"+b); //age:16
}
demo(a:"haha",b:"16",c:"160cm");
(4)设置函数参数的默认值
传统的设置参数默认值:
function demo(a){
var name;
if(a===undefined){
name="haha";
}else{
name=a;
}
console.log(name);
}
解构赋值设置参数默认值:
function demo({name="haha"}){
console.log(name);
}
demo({}); //haha
demo({name:"aa"}) //aa
—————————————————————————
参考公众号:web前端教程