目录
ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这个就称之为解构。
Spread/Rest操作符
Spread/Rest操作符指的是'...',具体'...'指的是哪一种,需要看在什么场景中使用。
①用于迭代器中
用于迭代器(迭代器是按照一定的顺序对一个或多个容器中的元素进行便利的一种机制)时,'...'是一个Spread操作符
function Fun(a,b,c){
console.log(a,b,c);
}
let arr = [1,2,3];
Fun(...arr); //1 2 3
②用于函数传参
用于函数传参时,'...'是一个Rest操作符
function Fun(...args){
console.log(args);
}
Fun(1,2,3,4,5,6); //[ 1, 2, 3, 4, 5, 6 ]
数组的解构赋值
使用方式
在ES5中我们对多个变量进行赋值通常是采用逐个赋值,ES6中允许我们从数组中提取值1,按照对应位置对变量进行赋值,这样很好地减少了代码量。
//ES6中对多个变量赋值
let [a,b,c] = [1,2,3]
本质上这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值,若解构失败,则会输出undefined,我们还可以多种形式进行解构:
①嵌套数组进行解构:
let [a,[[b],c]] = [1,[[2],3]];
console.log(a); //1
console.log(b); //2
console.log(c); //3
②不完全解构(等号左边的模式只匹配一部分等号右边的数组,这里指的是左边数量小于右边):
let [a,b] = [1,2,3];
console.log(a); //1
console.log(b); //2
③使用'...'进行解构:
let [e,...f] = [1,2,3,4,5];
console.log(e); //1
console.log(f); //[ 2, 3, 4, 5 ]
同时我们也要注意导致解构失败的情况
①不完全解构(等号左边的模式只匹配一部分等号右边的数组,这里指的是左边数量大于右边):
let [a,b,c] = [1,2];
console.log(a); //1
console.log(b); //2
console.log(c); //undefined
let [g,h,...i] = [1];
console.log(g); //1
console.log(h); //undefined
console.log(i); //[]
②等号右边不是数组(不是可遍历的解构)
//报错
let [a] = 1;
let [a] = {};
let [a] = NaN;
let [a] = true;
let [a] = null;
let [a] = undefined;
使用默认值
解构赋值允许指定默认值,我们在上面有提到,如果等号左边的变量数大于右边的指定值,那么左边多余的变量值输出就是undefined,如果不想多余的值输出undefined,我们可以事先指定默认值。
let [boolean = true] = [];
console.log(boolean); //true
let [a=1,b=2] = [3];
console.log(a); //3
console.log(b); //2
这里需要注意的是,ES6内部使用严格相等运算符(===)来判断一个位置是否有值。因此,只有当一个数组成员严格等于undefined,默认值才会生效。
let [a = 1] = [undefined];
console.log(a); //1
let [b = undefined] = [1];
console.log(b); //1
let [c = 2] = [null];
console.log(c); //null
上例中,由于数组成员1、null不是严格等于undefined,所以输出的是赋值,而不是默认值。第一个例子数组成员是undefined,所以输出的是默认值。
默认值还可以引用解构赋值的其他变量,但是该变量必须已经声明
let [a = 1,b = a] = [];
console.log(a); //1
console.log(b); //1
let [c = 1,d = c] = [2];
console.log(c); //2
console.log(d); //2
let [e = 1,f = e] = [2,3];
console.log(e); //2
console.log(f); //3
let [m = n,n = 1] = []; //ReferenceError: Cannot access 'n' before initialization
上述中最后一个表达式报错原因是因为:m用到n时,n还未声明。故默认值必须引用已经声明过的变量,若未声明,则解构失败。