1. 数组的解构赋值
基本用法:
let [a , b , c] = [1, 2, 3]
console.log(a);
let [head,...foot] = [1,2,3,4,5]
console.log(head);
console.log(foot);
let [a, [b], d] = [1, [2, 3], 4];
console.log(b);
let [a, [...b], d] = [1, [2, 3], 4];
console.log(b);
默认值:
let [foo = true] = [];
console.log(foo);
ES6 内部使用严格相等运算符(`===`),判断一个位置是否有值。
所以,只有当一个数组成员严格等于`undefined`,默认值才会生效。
let [x, y = 'b'] = ['a', undefined];
console.log(x,y);
如果一个数组成员是`null`,默认值就不会生效,因为`null`不严格等于`undefined`。
let [x = 1] = [null];
x
function f() {
console.log('aaa');
}
let [x = f()] = [1];
console.log(x);
上面代码中,因为`x`能取到值,所以函数`f`根本不会执行。上面的代码其实等价于下面的代码。
let x;
if ([1][0] === undefined) {
x = f();
} else {
x = [1][0];
}
ps:[1]看成一个数组a,a[0]=1,取第一个值
let [x = 1, y = x] = [];
let [x = 1, y = x] = [2];
let [x = 1, y = x] = [1, 2];
let [x = y, y = 1] = [];