zoukankan      html  css  js  c++  java
  • 数组的方法之(Array.prototype.reduce() 方法)

       reduce函数

    reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。

    对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果,并且此返回值下一次调用该回调函数时作为参数提供。

    <script>
      const array1 = [1, 2, 3, 4];
      const reducer = (accumulator, currentValue) => {
        console.log(accumulator +'|' + currentValue);
        return accumulator + currentValue
      };
      // 1 + 2 + 3 + 4
      console.log(array1.reduce(reducer));// 10
      // 5 + 1 + 2 + 3 + 4
      console.log(array1.reduce(reducer, 5));  // 15
      </script>

    输出如下:

    语法:

    callback 执行数组中每个值的函数,包含四个参数:

    • accumulator:累加器累加回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(如下所示)。
    • currentValue: 数组中正在处理的元素。
    • currentIndex: 可选,数组中正在处理的当前元素的索引。 如果提供了initialValue,则索引号为0,否则为索引为1。
    • array: 可选,调用reduce的数组。

    initialValue:可选,用作第一个调用 callback的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。

    用法如下

    1.常见用法:

      var t = [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
          console.log(accumulator + '|' + currentValue+ '-->' + currentIndex + '-->' + array);
          return accumulator + currentValue;
        });
        console.log('t:', t);

    输出如下:

    2. 如果你提供一个初始值作为reduce方法的第二个参数,以下是运行过程及结果:

     var t = [0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
          console.log(accumulator + '|' + currentValue+ '-->' + currentIndex + '-->' + array);
          return accumulator + currentValue; 
       }, 10 );
        console.log('t:', t);

    输出如下:

    3.将二维数组转化为一维

     var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
          function(a, b) {
            return a.concat(b);
          },[]);
       console.log(flattened);

     输出如下:

    4.计算数组中每个元素出现的次数

     var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
      var countedNames = names.reduce(function (allNames, name) { 
        console.log(allNames, '| ' + name);
        if (name in allNames) {
          allNames[name]++;
        } else {
          allNames[name] = 1;
        }
        return allNames; 
      }, {});
     console.log(countedNames);

    输出如下: 

    5.数组去重

    let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
      let result = arr.sort().reduce((init, current)=>{
          if(init.length===0 || init[init.length-1]!==current){
              init.push(current);
          }
    /*
    注意:使用push的话,必须return 这个变量init,如果return init.push()的话会报错;
    使用concat不存在这个问题,可以直接return a.concat(b);
    */ 
    return init; }, []); console.log(result); //[1,2,3,4,5]

    输出如下:

  • 相关阅读:
    [chrome]click事件会触发mouseleave
    鼠标的指针状态 以及 事件禁用
    CSS3 线性渐变(linear-gradient)
    css 的函数 calc() 、linear-gradient()、、、
    1.闰年的计算方法。 2.某一月的周数
    moment.js 使用方法总结
    Echarts 版本查看
    如何使用 onscroll / scrollTo() / scrollBy()
    水平居中、垂直居中
    【LeetCode】22. Generate Parentheses (I thought I know Python...)
  • 原文地址:https://www.cnblogs.com/xuzhudong/p/8886192.html
Copyright © 2011-2022 走看看