ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring),本质属于模式匹配
事实上,只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值。
js
// 斐波拉契数列
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
console.log(first)
console.log(second)
console.log(third)
console.log(fourth)
console.log(fifth)
console.log(sixth)