Array.reduce

来源:互联网 发布:爱古兰中阿文软件下载 编辑:程序博客网 时间:2024/05/18 02:01

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

语法

arr.reduce(callback,[initialValue])

参数

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

  1. accumulator 上一次调用回调返回的值,或者是提供的初始(initialValue)
  2. currentValue 数组中正在处理的元素
  3. currentIndex 数据中正在处理的元素索引,如果提供了 initialValue ,从0开始;否则从1开始
  4. array 调用 reduce 的数组

initialValue:可选项,其值用于第一次调用 callback 的第一个参数。

返回值

函数累计处理的结果

描述

reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值 accumulator (或者上一次回调函数的返回值),当前元素值 currentValue ,当前索引 currentIndex ,调用 reduce 的数组。

回调函数第一次执行时,accumulator 和 currentValue 的取值有两种情况:调用 reduce 时提供initialValue,accumulator 取值为 initialValue ,currentValue 取数组中的第一个值;没有提供 initialValue ,accumulator 取数组中的第一个值,currentValue 取数组中的第二个值。

注意: 不提供 initialValue ,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。提供 initialValue ,从索引0开始。

如果数组为空并且没有提供initialValue, 会抛出TypeError 。如果数组仅有一个元素(无论位置如何)并且没有提供initialValue, 或者有提供initialValue但是数组为空,那么此唯一值将被返回并且callback不会被执行。

  • 未指定initialValue
let sum = [1, 2, 3, 4].reduce(function(acc, val,index) {  console.log("index = "+index+",currentValue = " + val+",accumulator = " + acc);  return acc + val;});console.log(sum);

未指定initialValue

  • 指定initialValue
let sum = [1, 2, 3, 4].reduce(function(acc, val,index) {  console.log("index = "+index+",currentValue = " + val+",accumulator = " + acc);  return acc + val;},10);console.log(sum);

指定initialValue

0 0
原创粉丝点击