数组方法"reduce"有什么作用? [英] What does the Array method `reduce` do?

查看:146
本文介绍了数组方法"reduce"有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个非常有用的功能 reduce ,并且我正在使用它,但是我不确定我是否理解正确.谁能帮助我了解此功能?

I found a very useful function reduce, and I'm using it, but I'm not sure if I understand it properly. Can anyone help me to understand this function?

示例:

var arr = [ 1, 2, 3, 4, 5, 6 ];
arr.reduce(function(p,n){
    return p + n;
}, 0);
// Output 21

这是我的理解: reduce 遍历数组的每个元素,并返回 previous +当前值.前任. 0 + 1 1 + 2 等.在这种情况下,此函数将返回:

This is my understanding: reduce loops through every element of the array and returns previous + current value. Ex. 0 + 1, 1 + 2 etc. In this case this function will return:

[0] - return 1
[1] - return 3
[2] - return 5
[3] - return 7
[4] - return 9
[5] - return 11

接下来要做什么?为什么给出结果 21 ?

What next? Why does it give the result 21?

推荐答案

来自此处 arr.reduce()会将数组缩减为由回调指定的值.在您的情况下,它将基本上对数组的元素求和.步骤:

Taken from here, arr.reduce() will reduce the array to a value, specified by the callback. In your case, it will basically sum the elements of the array. Steps:

  • 在0,1上调用函数(0是作为第二个参数传递给 .reduce()的初始值.返回总和od 0和1,即1.
  • 对上一个结果(为1)和下一个数组元素调用函数.这将返回1和2之和,即3
  • 重复直到最后一个元素,该元素总计为21
  • Call function on 0,1 ( 0 is the initial value passed to .reduce() as the second argument. Return sum od 0 and 1, which is 1.
  • Call function on previous result ( which is 1 ) and next array element. This returns sum of 1 and 2, which is 3
  • Repeat until last element, which will sum up to 21

这篇关于数组方法"reduce"有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆