zoukankan      html  css  js  c++  java
  • ES6 解构对象和数组

    1.解构对象

    let saveFiled = {
      extension: "jpg",
      name:"girl",
      size:14040
    };
    
    ES5
    function fileSammary(file){
      return `${file.name}.${file.extension}的总大小是${file.size}`;
    }
    console.log(fileSammary(saveFiled));
    
    
    ES6
    function fileSammary({name,extension,size}){
      return `${name}.${extension}的总大小是${size}`;
    }
    
    console.log(fileSammary(saveFiled));
    

    2.解构数组

    1.返回数组第一位数值
    const names = ["Henry","Bucky","Emily"];
    
    ES5
    console.log(names[0])
    
    ES6
    const [name1,name2,name3] = names;
    console.log(name1)
    
    2.返回数组个数
    ES5
    console.log(names .length)
    
    ES6
    const { length } = names
    console.log(length)
    
    3.结合展开运算符
    const [name,...rest] = names;
    console.log(name, rest);
    
    4.对象数组
    const people = [
      {name:"Henry",age:20},
      {name:"Bucky",age:25},
      {name:"Emily",age:30}
    ];
    
    ES5
    var age = people[0].age;
    console.log(age);
    
    ES6
    const [age] = people;
    console.log(age)   //{name:"Henry",age:20}
    const [{age}] = people;
    console.log(age)   // 20
    
    5. 使用场景 将数组转化为对象
    const points = [
      [4, 5],
     [10, 1],
     [0, 40]
    ]
    // 期望数据格式
    [
      {x:4,y:5},
      {x:10,y:1},
      {x:0,y:40}
    ]
    
    ES6
    let newPoints = points.map(pair => {
      // const x = pair[0];
      // const y = pair[1];
      const [x,y] = pair;
      return {x,y}
    })
    
    let newPoints = points.map(([x, y]) => {
      // const x = pair[0];
      // const y = pair[1];
      // const [x,y] = pair;
      return { x, y }
    })
    
    console.log(newPoints)
    

      

  • 相关阅读:
    Codeforces Round #364
    HDU5727 Necklace
    bzoj4578: [Usaco2016 OPen]Splitting the Field
    Codeforces Round #363 (Div. 1) C. LRU
    BestCoder Round #84
    2014 Multi-University Training Contest 2
    php中 new self 和 new static的区别
    浏览器带着cookie去访问服务器,取出的数据为空
    左边用0填充补齐
    centos7修改密码
  • 原文地址:https://www.cnblogs.com/gqx-html/p/11277959.html
Copyright © 2011-2022 走看看