数组解构 - 模式匹配(结构化赋值)

let [a, b, c] = [1, 2, 3];
console.log(a, b, c);
// 1 2 3

let [d, [e], [f]] = [1, [2], [3]];

let [a, [b, c], [d, [e, f, [g]]]] = [1, [2, 3], [4, [5, 6, [7]]]];
console.log(a, b, c, d, e, f, g);
// 1 2 3 4 5 6 7

🌈 解构失败 - undefined 填充

let [a, [b, c], [d, [e, f, [g]]]] = [1, [2, ], [, [, 6, [7]]]];
console.log(a, b, c, d, e, f, g);

// 1 2 undefined undefined undefined 6 7

不完全解构

let [a, [b, ], [, [e, , [g]]]] = [1, [2, 3], [4, [5, 6, [7]]]];
console.log(a, b, e, g);

// 1 2 5 7

解构默认值

// 默认值给3
let [a = 3] = [1];

let [b = 3] = [];

let [a, b = 2] = [1]; // a = 1, b = 2

undefined 会被看做没有值,null 则不然

// undefined 会被认为没有传值
let [a, b = 2] = [1, undefined]; // a = 1, b = 2

let [a, b = 2] = [1, null]; // a = 1, b = null
function test() {
	console.log('test--', 10);
}

let [x = test()] = [1];

console.log('x--', x);

// 打印 'x-- 1'

let [y = test()] = [];

console.log('y--', y);

// 打印 test-- 10
// 接着打印 y-- undefined,因为 undefined 是函数的默认返回值
let [x = 1, y = x] = [];
console.log(x, y);

// 1 1
let x = 10;
let [x = 1, y = x] = [];

// 两次声明了x:Identifier 'x' has already been declared
let [x = 1, y = x] = [2];
console.log(x, y); // 2 2
let [x = 1, y = x] = [1, 2];
console.log(x, y); // 1 2
let [x = y, y = 1] = [];
console.log(x, y);
// 暂时性死区报错:
// Cannot access 'y' before initialization

数组也是特殊的对象,也可以进行解构赋值

let arr = [1, 2, 3];
let { 0: first, [arr.length - 1]: last } = arr;
console.log(first, last);

// 1 3

🌈 对象解构

let { a: a, b: b, c: c } = { a: 1, b: 2, c: 3 };
console.log(a, b, c); // 1 2 3

let { a, b, c } = { a: 1, b: 2, c: 3 };
console.log(a, b, c); // 1 2 3