ES6——数组的解构赋值
- 解构的定义
ES6允许按照一定模式从数组和对象中提取值,然后对变量进行赋值
在以前,为变量赋值只能直接指定,例如:
let a=1;
let b=2;
let c=3;
而自从ES6引入了解构赋值之后,可以下列这样定义变量:
let [d, e, f] = [4, 5, 6];
console.log(d, e, f); //4 5 6
console.log([d, e, f]); //[4,5,6]
上述代码就是从数组中提取值,按照对应位置对变量赋值,本质上,这种写法属于模式匹配,只要等号两边的模式相同,左边的变量就会被赋予对应的值
- 数组的解构赋值可以嵌套使用,如果解构不成功,变量的值就会返回undefined
let [x, [y, z]] = [1, [2, 3]];
console.log(x, y, z); //1 2 3
let [, , third] = ['a', 'b', 'c'];
console.log(third); //'c'
let [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head, tail); //1 [2,3,4,5]
let [m, n, ...o] = ['a'];
console.log(m); //'a'
console.log(n); //undefined
console.log(o); //[]
- 不完全解构
等号左边的模式只匹配一部分等号右边的数组,这种情况下依然可以解构成功
let [g, h] = [1, 2, 3];
console.log(g); //1
console.log(h); //2
console.log([g, h]); //[1,2]
- 解构赋值允许指定默认值
let [foo = true] = [];
console.log(foo); //true
let [x1, y1 = 'b'] = ['a', undefined];
console.log(x1); //'a'
console.log(y1); //'b'
- ES6内部使用严格相等运算符’==='判断一个位置是否有值。所以,如果一个数组成员不严格等于undefined,默认值是不会生效的
let [x2 = 1] = [undefined];
console.log(x2); //1
let [x3 = 1] = [null];
console.log(x3); //null
- 如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到时才会求值
function fn() {
console.log('aaa');
}
let [x4 = fn()] = [1];
console.log(x4); //1(x4能取到值,所以函数fn()根本不会执行)
/* 以上代码等价于 */
// let x4;
// if (([1][0]) === undefined) {
// x4 = fn();
// } else {
// x4 = [1][0];
// }
// console.log(x4);//1