码迷,mamicode.com
首页 > 编程语言 > 详细

ES6 - 解构(数组和对象)

时间:2019-12-12 23:46:00      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:script   读取   取数据   new   int   tps   var   AMM   http   

解构对象

/**
 * 解构:快捷,方便
 * 
 * 对象解构
 */

{
  var expense = {
    type: "es6",
    amount: "45"
  };

  //1.ES5
  // var type = expense.type;
  // var amount = expense.amount;
  // console.log(type, amount); //output: es6 45

  //2.ES6
  const { type, amount, abc } = expense;
  console.log(type, amount, abc);    //output: es6 45 undefined
}

{

  var saveFiled = {
    extension: "jpg",
    name: "girl",
    size: 14040
  };

  //ES5
  function fileSammary1(file) {
    return `${file.name}.${file.extension}的总大小是${file.size};`
  }

  //ES6
  //名字不能变,位置可以乱
  function fileSammary2({ name, size, extension }) {
    return `${name}.${extension}的总大小是${size};`
  }

  console.log(fileSammary1(saveFiled)); //output: girl.jpg的总大小是14040;
  console.log(fileSammary2(saveFiled)); //output: girl.jpg的总大小是14040;
}

其他参考:ECMAScript6 - 2.变量的解构赋值

解构数组

/**
 * 解构:快捷,方便
 * 
 * 数组解构
 */

/**
 * 基础
 */
{
  const names = ["Henry", "Bucky", "Emily"];
  const [name1, name2, name3] = names;
  console.log(name1, name2, name3);

  //用对象接收,反数组个数
  const { length } = names;
  console.log(length); // 3

  //结合张开运算符
  const [name, ...rest1] = names;
  console.log(name);  // Henry
  console.log(rest1); //(2) ["Bucky", "Emily"]

  let [foo, [[bar], baz]] = [1, [[2], 3]];
  foo; // 1
  bar; // 2
  baz; // 3
}

/**
 * 数组中的对象
 */
{
  //对象数组
  const people = [
    { name: "Henry", age: 20 },
    { name: "Bucky", age: 25 },
    { name: "Emily", age: 30 }
  ];

  // ES5
  //读取数据元素中的对象参数值
  {
    var age = people[0].age;
    age;      // 20
  }

  // ES6
  {
    //读取数组的元素
    {
      const [age1, , age] = people;
      console.log(age1);  // { name: "Henry", age: 20 },
      console.log(age);   // { name: "Emily", age: 30 }
    }

    //读取数组元素中的对象参数值
    {
      const [{ age }] = people;
      console.log(age);   // 20
    }
  }


  //数组转化为对象
  {
    const points = [
      [4, 5], [10, 20], [0, 100]
    ];

    /**
     * 期望数据格式:
     * [
     *  {x:4,y:5},
     *  {x:10,y:20},
     *  {x:0,y:100}
     * ]
     */

     let newPoints = points.map(([x,y])=>{
       //1.传入解构 [x,y] = [4,5]
       //2.x = 4, y = 5
       //3.return {x:x,y:y} 简写 return {x,y}
       return {x,y};
     })

     console.log(newPoints);
  }
}

ES6 - 解构(数组和对象)

标签:script   读取   取数据   new   int   tps   var   AMM   http   

原文地址:https://www.cnblogs.com/tangge/p/12032182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!