从数组和对象中提取值,对变量进行赋值,这被称为解构
let [foo, [[bar], baz]] = [1, [[2], 3]];foo // 1bar // 2baz // 3let [ , , third] = ["foo", "bar", "baz"];third // "baz"let [x, , y] = [1, 2, 3];x // 1y // 3let [head, ...tail] = [1, 2, 3, 4];head // 1tail // [2, 3, 4]let [x, y, ...z] = ['a'];x // "a"y // undefined // 如果解构不成功,变量的值就等于undefinedz // []
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 // truelet [x, y = 'b'] = ['a']; // x='a', y='b'let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'let [x = 1] = [undefined]; // x // 1let [x = 1] = [null]; //x // null