5.ES6解构赋值-字符串、数值和布尔值、函数

什么是解构赋值

案例(字符串、数值和布尔值、函数)解构赋值:

  // 字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象
  const [a, b, c, d] = 'javascript'
  console.log('a == %s, b == %s, c == %s, d == %s,', a, b, c, d); //a == j, b == a, c == v, d == a,
  // 类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。
  let {length : len} = 'javascript';
  console.log('len == %s', len);

  // 数值和布尔值的解构赋值
  // 解构赋值时,如果等号右边是数值和布尔值,则会先转为对象
  let {toString: s} = 123;
  console.log(' s == number, %b', s === Number.prototype.toString); // true

  let {toString: t} = true;
  console.log(' s == boolean, %b', t === Boolean.prototype.toString); // true
  // 解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错
  //let {p: x} = null; //property 'p' of null
  //let {p: x} = undefined; // Cannot read property 'p' of undefined
  //console.log(x);

  // 函数参数的解构赋值
  function add([x, y]) {
    return x + y;
  }
  console.log('add() == %s', add([5, 6]));
  let rs = [[1, 3], [4, 6]].map(([a , b]) => a + b);
  console.log('rs == %a', rs); //4, 10
  // 函数参数的解构也可以使用默认值。
  // 函数add2的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值,如果解构失败,x和y等于默认值
  function add2({x = 0, y = 0} = {}) {
    return [x, y];
  }
  console.log('add2() == %a', add2({x:3, y: 4})); //[3, 4]
  console.log('add2() == %a', add2({y: 4})); //[0, 4]
  console.log('add2() == %a', add2({})); //[0, 0]
  console.log('add2() == %a', add2()); //[0, 0]

  // 为函数add3的参数指定默认值,而不是为变量x和y指定默认值
  function add3({x, y} = {x:0, y:0}) {
    return [x, y];
  }
  console.log('add3() == %a', add3({x:3, y: 4})); //[3, 4]
  console.log('add3() == %a', add3({x:3})); //[3, undefined]
  console.log('add3() == %a', add3({})); //[undefined, undefined]
  console.log('add3() == %a', add3()); //[0, 0]

  // 变量的解构赋值用途很多
  // 1.交换变量的值
  let x = 1, y = 2;
  [x, y] = [y, x];
  console.log('x == %s, y == %s', x, y);
  // 2.从函数返回多个值
  function add4() {
    return [1, 2, 3];
  }
  let [a1, b1, c1] = add4()
  console.log('a1 == %s, b1 == %s, c1 == %s ', a1, b1, c1); // a1 == 1, b1 == 2, c1 == 3
  // 返回对象
  function add5() {
      return {
        f1: '001',
        b3: '002'
      }
  }
  let {f1: f3 , b3} = add5();
  console.log('f3 == %s, b3 == %s', f3, b3);

  // 3.提取 JSON 数据
  let jsonstr = {
      a11: 'a1',
      b11: [1, 2, 3],
      c11: {
        name: 'zs',
        title: 'title1'
      }
  }
  let {a11, b11, c11} = jsonstr;
  console.log('a11 ==  %s, b11 == %o, c11 == %o', a11, b11, c11);
    原文作者:圆梦人生
    原文地址: https://www.jianshu.com/p/7e86d94c74ff
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞