es6允许按照一定模式,从数组和对象中提取值(大部分的解构都是用于二者的,还有一个Set解构),对变量进行赋值,被称为解构
let [a,b,c] = [1,2,3] // 数据解构,位置一一对应,赋予相应的值
若是位置空出来,则不会进行赋值
let [a,b,c,] = [1,2,3,4] // 其中a=1,b=2,c=3,用于遵循位置一一对应的原则
let [head, ...tail] = [1,2,3,4] // head=1 , tail = [2,3,4] 扩展运算符,位置对应,后面的合成一个数组赋值给tail
若没有对应的值,表示解构失败,将会赋值undefined
let [foo] = []; // foo = undefined
let [bar, foo] = [1]; // for = undefined
解构不完全也是遵循位置对应,例如:
let [x, y] = [1, 2, 3];
x // 1
y // 2
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
事实上,只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值。(暂时看不懂)
function* fibs() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
let [first, second, third, fourth, fifth, sixth] = fibs();
sixth // 5
在解构的时候是允许指定默认值。
let [foo = true] = []; // 若解构为undefined,将会默认foo为true
let [ foo = true, name = "1"] = [1, 2] // 具备对应的解构值,不会执行默认值
// null与undefined是不同的
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
// 还可以解构出函数
function f(){
console.log("aaa")
}
let [name = f()] = [] // aaa (打印出aaa)
默认解构值还可以使用前者的默认值,前者必须已经定义,但是前者不能使用后者的定义值
let [x = 1, y = x] = []; // x=1; y=1
let [x = 1, y = x] = [2]; // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = []; // ReferenceError: y is not defined