• 变量的解构赋值
    • 对象的解构赋值 

          let arr = [1, 2, 3];
          let {0 : first, [arr.length - 1] : last} = arr;
          first // 1
          last // 3
    • 段落的解构赋值

           字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。

          const [a, b, c, d, e] = 'hello';
          a // "h"
          b // "e"
          c // "l"
          d // "l"
          e // "o"
      

          类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

          let {length : len} = 'hello';
          len // 5
    •  函数参数的解构赋值

           

      function move({x = 0, y = 0} = {}) {
        return [x, y];
      }
      
      move({x: 3, y: 8}); // [3, 8]
      move({x: 3}); // [3, 0]
      move({}); // [0, 0]
      move(); // [0, 0]
      

      上面代码中,函数move的参数是一个对象,通过对这个对象进行解构,得到变量xy的值。如果解构失败,xy等于默认值。

      注意,下面的写法会得到不一样的结果。

      function move({x, y} = { x: 0, y: 0 }) {
        return [x, y];
      }
      
      move({x: 3, y: 8}); // [3, 8]
      move({x: 3}); // [3, undefined]
      move({}); // [undefined, undefined]
      move(); // [0, 0]
      

       上面代码是为函数move的参数指定默认值,而不是为变量xy指定默认值,所以会得到与前一种写法不同的结果。

       undefined就会触发函数参数的默认值。

      [1, undefined, 3].map((x = 'yes') => x);
      // [ 1, 'yes', 3 ]