reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。

arr.reduce([callback, initialValue])
callback
执行数组中每个值的函数,包含四个参数:
previousValue
上一次调用回调函数返回的值,或者是提供的初始值(initialValue)
currentValue
数组中当前被处理的元素
currentIndex
当前被处理元素在数组中的索引, 即currentValue的索引.如果有initialValue初始值, 从0开始.如果没有从1开始.
array
调用 reduce 的数组
initialValue
可选参数, 作为第一次调用 callback 的第一个参数。

返回值

最后一次调用回调函数返回的结果

reduce是如何工作的

例如执行下面的代码
[, , , , ].reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
回调被执行四次,每次的参数和返回值如下表:

 	   previousValue  currentValue	index	array	  return value
first call 0 1 1 [0,1,2,3,4] 1
second call 1 2 2 [0,1,2,3,4] 3
third call 3 3 3 [0,1,2,3,4] 6
fourth call 6 4 4 [0,1,2,3,4] 10

  reduce 的返回值是回调函数最后一次被调用的返回值(10)。

用箭头函数也可以的
[, , , , ].reduce( (prev, curr) => prev + curr );

如果把初始值作为第二个参数传入 reduce,结果如下,结果如下:


[,,,,].reduce( (previousValue, currentValue, currentIndex, array) => {
return previousValue + currentValue;
}, );

 	      previousValue	currentValue	index	       array	return value
first call 10 0 0 [0,1,2,3,4] 10
second call 10 1 1 [0,1,2,3,4] 11
third call 11 2 2 [0,1,2,3,4] 13
fourth call 13 3 3 [0,1,2,3,4] 16
fifth call 16 4 4 [0,1,2,3,4] 20

  最后一次函数调用的返回值 (20) 作为reduce函数的结果被返回.


例题
将数组所有项相加
var total = [, , , ].reduce(function(a, b) {
return a + b;
}, );
// total == 6
或者用箭头函数这样写: var total = [ , , , ].reduce( ( acc, cur ) => acc + cur, );
扁平化一个二维数组
var flattened = [[, ], [, ], [, ]].reduce(function(a, b) {
return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]

兼容旧环境(Polyfill)
Array.prototype.reduce 被添加到 ECMA- 标准第 版;因此可能在某些实现环境中不被支持。可以将下面的代码插入到脚本开头来允许在那些未能原生支持 reduce 的实现环境中使用它。
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(callback /*, initialValue*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
var t = Object(this), len = t.length >>> , k = , value;
if (arguments.length == ) {
value = arguments[];
} else {
while (k < len && !(k in t)) {
k++;
}
if (k >= len) {
throw new TypeError('Reduce of empty array with no initial value');
}
value = t[k++];
}
for (; k < len; k++) {
if (k in t) {
value = callback(value, t[k], k, t);
}
}
return value;
};
}
 

Array.prototype.reduce()的更多相关文章

  1. js Array​.prototype​.reduce()

    例子: , , , ]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 ...

  2. Array.prototype.reduce 的理解与实现

    Array.prototype.reduce 是 JavaScript 中比较实用的一个函数,但是很多人都没有使用过它,因为 reduce 能做的事情其实 forEach 或者 map 函数也能做,而 ...

  3. [JavaScript] Array.prototype.reduce in JavaScript by example

    Let's take a closer look at using Javascript's built in Array reduce function. Reduce is deceptively ...

  4. 数组的方法之(Array.prototype.reduce() 方法)

    reduce函数 reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值. 对数组中的所有元素调用指定的回调函数.该回调函数的返回值为累积结果,并且此返回值在下一次 ...

  5. 数组方法 Array.prototype

    Object.prototype 数组的值是有序的集合,每一个值叫做元素,每一个元素在数组中都有数字位置编号,也就是索引,js中数组是弱类型的,数组中可以含有不同类型的元素.数组元素甚至可以是对象或者 ...

  6. 来自数组原型 Array.prototype 的遍历函数

    1. Array.prototype.forEach() forEach() 是一个专为遍历数组而生的方法,它没有返回值,也不会改变原数组,只是简单粗暴的将数组遍历一次  参数: callback() ...

  7. Array.prototype

    Array.prototype  属性表示 Array 构造函数的原型,并允许您向所有Array对象添加新的属性和方法. /* 如果JavaScript本身不提供 first() 方法, 添加一个返回 ...

  8. JavaScript,通过分析Array.prototype.push重新认识Array

    在阅读ECMAScript的文档的时候,有注意到它说,数组的push方法其实不仅限于在数组中使用,专门留作通用方法.难道是说,在一些类数组的地方也可以使用?而哪些是和数组非常相像的呢,大家或许一下子就 ...

  9. 使用Array.prototype.indexOf()的几点注意

    对应indexOf这个方法,在日常开发中比较常见的应该是String.prototype.indexOf()方法,Array.prototype.indexOf()方法和其有很大的相似性,本文不想去描 ...

随机推荐

  1. IIS配置HTTPS

    1,新建网站,选中类型为 https,然后更改SSL证书为你配置的SSL证书, 对于SSL证书的配置是这样的 点开第二步,然后点击 创建自签名证书 确定以后点开网站看到有个SSL, 双击进去,再选中 ...

  2. Log4Net使用学习笔记

    项目源文件下载https://files.cnblogs.com/files/ckym/Log4NetTestSourceCode.zip Log4net是一款非常好用的日志记录的框架,使用它可以实现 ...

  3. vb.net MakeWParam

    Private Function MakeWParam(loWord As Integer, hiWord As Integer) As Integer ) End Function

  4. Java设计模式——适配器模式(Adapter)

    目的:把源类型适配为目标类型,以适应客户端(Client)的需求:此处我们把目标接口的调用方视为客户端 使用场景:需要对类型进行由源类型到目标类型转换的场景中 前置条件:已有客户端 //Client ...

  5. Snapde怎么添加行和列

    Snapde,一个专门为编辑超大型数据量CSV文件而设计的单机版电子表格软件:它运行的速度非常快,反应非常灵敏.那么它是如何添加行列的呢? 它有三种方法可以添加: 1.在编辑下拉菜单下找到设置行列数菜 ...

  6. Edge BUG欣赏之四摸鸡与IP地址的恩怨

    <html><head>     <meta http-equiv="Content-Type" content="text/html; c ...

  7. JMeter中文返回乱码

    JMeter中文返回乱码 结果树响应数据中文返回乱码 其实有几个方法: 在线程组->http请求的字符集里设置 ​ 在http 消息管理头中设置 ​ 3.如果以上方法还没有解决,请打开安装目录 ...

  8. whistle

    whistle介绍 whistle是基于Node的跨平台web调试代理工具, 主要查看, 修改HTTP, HTTPS, Websocket的请求,响应, 也可以作为HTTP代理服务器使用 (文档)[h ...

  9. jsp用el表达式获取后台传来的值,或者获取session中的值

    <script type="text/javascript"> var usernameC = ${sessionScope.SESSION_USER_PROFILE. ...

  10. 【原】Java学习笔记006 - 流程控制

    package cn.temptation; public class Sample01 { public static void main(String[] args) { // 需求:写一万次&q ...