数组解构
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
z // []
对象解构
// 例一
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
// 例二
let { log, sin, cos } = Math;
值类型的解构
- 字符串解构赋值
- 字符串被转换成了一个类似数组的对象 ```javascript // 案例一 const [a, b, c, d, e] = ‘hello’; a // “h” b // “e” c // “l” d // “l” e // “o”
// 案例二 let {length : len} = ‘hello’; len // 5
- 数值和布尔值的解构赋值
- 数值和布尔值,则会先转为对象
```javascript
let {toString: s} = 123;
// new Number()的实例对象中,有toString方法,将它赋给s
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true