JavaScript - reduce()函数的示例 [英] JavaScript - examples of reduce() function

查看:87
本文介绍了JavaScript - reduce()函数的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看这个使用reduce()函数的例子。

I'm looking at this example of use of reduce() function.

function add(runningTotal, currentValue) {
   return runningTotal + currentValue;
}

var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce(add);
print(sum); // displays 55

你能告诉我一些使用reduce()的其他例子 - 我是不确定我是否完全遵循它是如何运作的。

Could you give show me some other examples of using reduce() - I'm not sure I fully follow how it works.

谢谢

推荐答案

减少的是采用 initialValue 函数,包含2个基本参数(可能需要更多)和列出的值。如果没有提供 initialValue ,则假定它是列表的第一个元素。该函数应该用 previousValue 做一些事情,通常用作累加器和 nextValue

What reduces does is take an initialValue, a function with 2 essential parameters (can take more) and a list of values. If no initialValue is provided then it's assumed it's the first element of the list. The function is supposed to do something with the previousValue usually used as an accumulator and the nextValue.

所以,假设你有一个值列表: [1,2,3,4,5] 并且该函数应该是添加2个参数和一个 initialValue 0

So, assume you have a list of values: [1, 2, 3, 4, 5] and the function is supposed to add the 2 parameters and an initialValue of 0.

第一步:

0 + 1 = 1
    2
    3
    4
    5

第二步:

1 + 2 = 3
    3
    4
    5

第三步:

3 + 3 = 6
    4
    5

第四步:

6 + 4 = 10
    5

第五步:

10 + 5 = 15 //Final value

如您所见,输入从列表转到单个值,因此名称 reduce 。在你的例子中,没有 initialValue (这是第二个参数),所以就像在第二步开始一样。

As you can see, the input went from a list to a single value, hence the name reduce. In your example, there's no initialValue (that's the second argument), so it's as if started on the second step.

这篇关于JavaScript - reduce()函数的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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