zoukankan      html  css  js  c++  java
  • es6数组方法详解

    Array在ES5新增的方法中,参数都是function类型,默认有传参(对应项,对应的索引,数组本身)

    因都为数组操作,我就在这里先声明所属变量,不必每次声明了

    let fruits = ['apple', 'banana', 'orange'];
    let people = [
      {
    "name" : "kobe" ,
    "age" : 36
      },
      {
    "name" : "jordan" ,
    "age" : 40
      },
      {
    "name" : "james" ,
    "age" : 34
      }
     ] 

    1. forEach

     [].forEach(function(value, index, array) {
        // ...
     });

        forEach方法 遍历数组元素

     fruits.forEach(function(fruit,index) { 
        console.log(fruit,index);          // apple,0  // banana,1  // orange,2
     });

    2. map   

        映射(一一对应)。

    [].map(callback,[ thisObject]);

     callback必须有return值(如果没有,则返回undefined),下面介绍三个实例来了解一下吧

    let arr1 = fruits.map(item=>(
        item.toUpperCase()
    ))
    console.log(arr1); // ["APPLE", "BANANA", "ORANGE"]


    let arr2 = people.map(item=>(
    item.age
    ));
    console.log(arr2); // [36, 40, 34]

    var arr3 = people.map(item=>({
    age : item.age
    }));
    console.log(arr3); //[{"age" : 36},{"age" : 40},{"age" : 34}]

    3. filter

     过滤筛选(callback中通过返回true 或 false而filter从而返回所有符合过滤条件的元素)。

    [].filter(callback,[ thisObject]);
    let arr4= people.filter(item=>(
      item.age>36
    )); console.log(arr4); // [{age:40,name:"jordan"}]

    4. reduce 

       数组中的每个值(从左到右)开始缩减,最终计算为一个值。

       回调参数中的值 pre,cur.,curIndex,arr ( 上一次计算的值,当前项,当前索引,数组);

      initialValue 初始值可选项

    [].reduce(callback[,initialValue]);
    let total = people.reduce((pre,cur,currentIndex)=>(
      pre+cur
    ),0); console.log( tobal ); // 110

    5. reduceRight 

      跟reduce方法完全一样,顺序为右开始计算

    git 地址 : https://github.com/freshPork/grunt/blob/master/es6-array.html

    作者:MF 孟飞 ; 如果文中有什么错误,欢迎指正,谢谢!
  • 相关阅读:
    codeblocks 更换颜色主题
    python3 回顾笔记1
    linux查找目录下的所有文件中是否含有某个字符串
    jupyter notebook 远程访问
    ubuntu ufw防火墙
    加载大量的xml数据 使用压缩方法解决(当然较小时也可以压缩)
    lua string介绍
    Lua和C++交互详细总结
    编写高性能的 Lua 代码
    lua中遍历table的几种方式比较
  • 原文地址:https://www.cnblogs.com/mileSs/p/8078820.html
Copyright © 2011-2022 走看看