数组解构

  1. let [foo, [[bar], baz]] = [1, [[2], 3]];
  2. foo // 1
  3. bar // 2
  4. baz // 3
  5. let [ , , third] = ["foo", "bar", "baz"];
  6. third // "baz"
  7. let [x, , y] = [1, 2, 3];
  8. x // 1
  9. y // 3
  10. let [head, ...tail] = [1, 2, 3, 4];
  11. head // 1
  12. tail // [2, 3, 4]
  13. let [x, y, ...z] = ['a'];
  14. x // "a"
  15. y // undefined
  16. z // []

对象解构

  1. // 例一
  2. let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
  3. foo // "aaa"
  4. bar // "bbb"
  5. // 例二
  6. 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

  1. - 数值和布尔值的解构赋值
  2. - 数值和布尔值,则会先转为对象
  3. ```javascript
  4. let {toString: s} = 123;
  5. // new Number()的实例对象中,有toString方法,将它赋给s
  6. s === Number.prototype.toString // true
  7. let {toString: s} = true;
  8. s === Boolean.prototype.toString // true