1 数组的解构赋值
赋值还能解构?到底是个什么东东?
let a,b;
[a,b] = [1,2];
console.log(a,b);//1 2
...
操作符的解构赋值
let a,b,restArr;
[a,b,...restArr] = [1,2,3,4,5,6];
console.log(a,b);//1 2
console.log(restArr);//[3,4,5,6]
let c;
[...c] = restArr;
console.log(c);//[3,4,5,6]
console.log(c===restArr);//false
2 对象的解构赋值
let {a,b} = {a:1,b:2};
console.log(a,b);//1,2
let {c,d} = {a:1,b:2};
console.log(a,b);//1,2
在结构对应的前提下,变量名不一定要对应。
...
操作符在对象解构赋值中的应用
let {a,b,...c} = {a:1,b:2,c:3,d:4};
console.log(a,b,c);//1,2 {c:3,d:4}
3 解构时可给定默认值
变量声明完成后,尽量给其初始化一个值,语言可以明确知道变量的类型和大小,减少存储难度。
let [a=0,b=0,c=0] = [1,2];
console.log(a,b,c);//1 2 0
4 轻松实现变量交换
let a = 1;
let b = 2;
[b,a] = [a,b];
console.log(a,b);//2 1
5 灵活承接函数返回值
function fn(){
return [1,2,3,4,5,6];
}
let [a,b,...c] = fn();
console.log(a,b,c);//1 2 [3,4,5,6]
6 复杂数据结构解构时的key:value形式
let {a:var1,b:var2} = {a:1,b:2};
console.log(var1,var2);//1 2
复杂点的数据结构只需结构和key对应即可
let {a:var1,b:var2,c:{name:var3}} = {
a:1,
b:2,
c:{name:'zhangsan',age:18},
count:[50,60,89]
};
console.log(var3);//zhangsan
ES6总篇--目录