zoukankan      html  css  js  c++  java
  • js数组篇2----ECMASCript5为数组定义了5个迭代方法和归并方法reduce()和reduceRght()

    数组定义了5个迭代方法和归并方法

    上一篇总结数组的基础用法,感兴趣可以可以看之前总结:
    今天主要总结一下ECMASCript5为数组定义了5个迭代方法和归并方法reduce()和reduceRght()

    一、ECMASCript5为数组定义了5个迭代方法

    1、every():对数组中的每一项运行给定的函数,如果该函数对每一项都返回true,则返回true。
    2、filter():对数组中的每一项运行给定函数,返回该函数会返回true的项目组成的数组。
    3、forEach():对数组中的每一项运行给定的函数。这个方法没有返回值。
    4、map():对数组中的每一项给定函数,返回每次调用返回结果的数组
    5、some():对数组中的每一项运行给定函数,如果该函数对任意项返回true,则返回true
    let  numbers = [1,2,3,4,5];
    let  everyRes = numbers.every(function(item, index, array){
          return (item>2);
    });
    console.log('--every--', everyRes);// false
                
    let filterRes = numbers.filter(function(item, index, array){
        return (item>3);
    });
    console.log('--filter--', filterRes);// [4, 5]
                
    numbers.forEach(function(item,index,array){
        console.log('--forEach--', item, index, array);//
    });
    
    let mapRes = numbers.map(function(item,index,array){
        return item*2;
    });
    console.log('--map--', mapRes);//[2, 4, 6, 8, 10]
    let mapRes = numbers.map(function(item,index,array){
         return item>3;
    });
    console.log('--map--', mapRes);//[false, false, false, true, true] 
    var someRes = numbers.some(function(item,index,array){
        return (item>2);
    });
    console.log('--some--', someRes);//true

    二、归并方法

    ECMASCript5 新增两个归并数组的方法reduce()和reduceRght()
    两个数组都会迭代数组所有项,然后构建一个最终返回值。
    其中,reduce() 方法从数组的第一项开始,逐个遍历到最后 reduceRght()方法从数组的第后一项开始,向前遍历到第一项
    语法:
    arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
    callback
        执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:
        accumulator
        累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(见于下方)。
        currentValue
        数组中正在处理的元素。
        index 可选
        数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始。
         array可选
         调用reduce()的数组
    initialValue可选
    作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。

    2.1、数组里所有值的和

    let sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
      return accumulator + currentValue;
    }, 0); // sum 6
    
    //箭头函数的形式:
    let total = [ 0, 1, 2, 3 ].reduce(
      ( acc, cur ) => acc + cur,
      0
    );

    2.2、累加对象数组里的值

    let  initialValue = 0;
    let sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
        return accumulator + currentValue.x;
    },initialValue)
    
    console.log(sum) // logs 6
    
    //你也可以写成箭头函数的形式:
    let initialValue = 0;
    let sum = [{x: 1}, {x:2}, {x:3}].reduce(
        (accumulator, currentValue) => accumulator + currentValue.x
        ,initialValue
    );
    
    console.log(sum) // logs 6

    2.3、将二维数组转化为一维

    let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
      function(a, b) {
        return a.concat(b);
      },
      []
    );
    // flattened is [0, 1, 2, 3, 4, 5]
    //你也可以写成箭头函数的形式:
    let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
     ( acc, cur ) => acc.concat(cur),
     []
    );

    2.4、计算数组中每个元素出现的次数

    //计算数组中每个元素出现的次数
    let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
    let countedNames = names.reduce(function (allNames, name) { 
      if (name in allNames) {
        allNames[name]++;
      }
      else {
        allNames[name] = 1;
      }
      return allNames;
    }, {});
    //countedNames is:
    // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

     2.5、按属性对object分类

    let people = [
      { name: 'Alice', age: 21 },
      { name: 'Max', age: 20 },
      { name: 'Jane', age: 20 }
    ];
    
    function groupBy(objectArray, property) {
      return objectArray.reduce(function (acc, obj) {
          console.log(acc, obj)
        var key = obj[property];
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(obj);
        return acc;
      }, {});
    }
    
    var groupedPeople = groupBy(people, 'age');
    
    ------->result::
    groupedPeople is:
    { 
      20: [
        { name: 'Max', age: 20 }, 
        { name: 'Jane', age: 20 }
      ], 
      21: [{ name: 'Alice', age: 21 }] 
    }

     
  • 相关阅读:
    多线程学习
    Redis学习2
    Redis学习1
    封装
    创建对象内存分析
    稀疏数组
    反转数组、冒泡排序
    可变参数
    .net core 3.x Web Api + Docker个人练手项目
    .net 性能优化手段
  • 原文地址:https://www.cnblogs.com/pikachuworld/p/12405200.html
Copyright © 2011-2022 走看看