变量的解构赋值

2020-04-28  本文已影响0人  东方三篇

数组的解构赋值

对象的解构赋值

字符串的解构赋值

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

  let {length : len} = 'hello';
  len // 5

数值和布尔值的解构赋值

  let {toString: s} = 123;
  s === Number.prototype.toString // true

  let {toString: s} = true;
  s === Boolean.prototype.toString // true
  # 数值和布尔值的包装对象都有toString属性,因此变量s都能取到值。
  let { prop: x } = undefined; // TypeError
  let { prop: y } = null; // TypeError

函数的参数解构赋值

  function add([x, y]){
    return x + y;
  }
  add([1, 2]); // 3

  [[1, 2], [3, 4]].map(([a, b]) => a + b);
  // [ 3, 7 ]

  # 函数add的参数表面上是一个数组,但在传入参数的那一刻,数组参数就被解构成变量x和y。对于函数内部的代码来说,它们能感受到的参数就是x和y。
  function move({x = 0, y = 0} = {}) {
    // = 号右面的 {} 才是传入的参数, 左侧只是 对 右侧 {} 的 加了 默认值 的解构 相当于 给变量 x y 赋了默认值
    return [x, y];
  }
  move({x: 3, y: 8}); // [3, 8]
  move({x: 3}); // [3, 0]
  move({}); // [0, 0]
  move(); // [0, 0]

  # 函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,x和y等于默认值。
  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的参数指定默认值,而不是为变量x和y指定默认值,所以会得到与前一种写法不同的结果。
  [1, undefined, 3].map((x = 'yes') => x);
  // [ 1, 'yes', 3 ]
  # undefined 就会触发函数参数的默认值。
上一篇 下一篇

猜你喜欢

热点阅读