es6-变量的解构赋值

从数组和对象中提取值,对变量进行赋值,这被称为解构

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

let [ , , third] = ["foo", "bar", "baz"];
third // "baz"

let [x, , y] = [1, 2, 3];
x // 1
y // 3

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined  // 如果解构不成功,变量的值就等于undefined
z // []
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();
// 0,1,1,2,3,5
let [x, y, z] = new Set(['a', 'b', 'c']); // set,不重复的数组
x // "a"

允许指定默认值当一个数组成员严格等于undefined,默认值才会生效

let [foo = true] = []; // foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
let [x = 1] = [undefined]; // x // 1
let [x = 1] = [null]; //x // null
原文地址:https://www.cnblogs.com/avidya/p/10636664.html