zoukankan      html  css  js  c++  java
  • javascript的数组之reduce()

    reduce()方法对累加器和数组中的每个元素(从左到右)应用到一个函数中,最终得到一个值并返回

     1 const array1 = [1, 2, 3, 4];
     2 const reducer = (accumulator, currentValue) => accumulator + currentValue;
     3 
     4 // 1 + 2 + 3 + 4
     5 console.log(array1.reduce(reducer));
     6 // expected output: 10
     7 
     8 // 5 + 1 + 2 + 3 + 4
     9 console.log(array1.reduce(reducer, 5));
    10 // expected output: 15

    参数:

    第一个:callback回调函数(accumulator, currentValue, currentIndex, array)

    第二个:initalValue初始值,作为第一个执行回调函数的accumulator值,reduce的index初始索引为0。如果没有initalValue,则使用数组第一个元素作为accumulator值,并且从第二个元素开始执行回调函数,此时reduce初始索引为1。

    返回值:函数累计的数组元素叠加值。

  • 相关阅读:
    pwd命令
    python-windows环境安装
    python介绍
    elk安装
    elk介绍
    111
    使用CEF作为用户界面
    使用CEF作为浏览器
    c# 内嵌chrome(Webkit)
    待搞清楚
  • 原文地址:https://www.cnblogs.com/huanqiuxuexiji/p/9167996.html
Copyright © 2011-2022 走看看