用vue.js学习es6(三):数组、对象和函数的解构

时间:2023-03-08 15:42:08

一.数组的解构:

  以前的方式:

  var arr = [1,2,3];

  console.log(arr[0]); //1

  console.log(arr[1]); //2

  现在的方式:

  var [a,b,c] = [1,2,3];

  console.log(a); //1

  console.log(b); //2

  数组解构还有以下几种:

  (1).

  var [a,[b,c]] = [1,[2,3]];
  //1
  console.log(a);
  //2
  console.log(b);
  //3
  console.log(c);

  (2).

  var [a,b,c] = new Set([4,5,6]);
  //4
  console.log(a);
  //5
  console.log(b);
  //6
  console.log(c);

  (3).

  var [a=1,b=a] = [];
  //1
  console.log(a);
  //1
  console.log(b);

  (4).

  var [a=1,b=a] = [2,3];
  //2
  console.log(a);
  //3
  console.log(b);

  

二.对象的解构赋值:  

  以前的方式
  var json = {
    a:1,
    b:2
  };  

  现在的方式:

  //name是a的别名
  var {a:name,b} = {a:3,b:4};
  var {a,b} = {a:3,b:4};
  var {a,b} = {a:1,b:[2,3]};

  例: 

  var json = {
    a:[
      'hi',
      {b:'hello'}
    ]
  };

  var {a:[name,{b}]} = json;
  //hi
  console.log(name);
  //hello
  console.log(b);

三.函数的解构赋值:

  以前的方式:
  function fn(a,b){
    console.log([a,b]);
  }
  //[1,2]
  fn(1,2); 

  现在的方式:

  (1).

  function fn([a,b]){
    console.log([a,b]);
  }
  fn([3,4]);//[3, 4]

  (2).

  function fn({a=1,b=2} = {}){
    console.log([a,b]);
  }

  fn(); //[1, 2]
  fn({a:1}); //[1, 2]
  fn({a:10,b:11}); //[10, 11]

  (3).

  function fn({a,b} = {a:1,b:2}){
    console.log([a,b]);
  }
  fn(); //[1, 2]
  fn({a:1}); //[1, undefined]
  fn({a:10,b:11}); //[10, 11]