Array.reduce如何将函数作为参数放入函数组合中? [英] How Array.reduce put functions as parameters in function composition?

查看:67
本文介绍了Array.reduce如何将函数作为参数放入函数组合中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释Array.reduce如何将函数作为参数放入函数组合中,如下所示:

Can somebody explain to me how Array.reduce can put functions as arguments in function composition like this:

const  composeB  = (f, g) =>  x  =>  f(g(x))

const  add = a => b => a  +  b
const  add5 = add(5)
const  double = a => a * 2

const add5ThenDouble  = [double, add5].reduce(composeB)

console.log(add5ThenDouble(6)); // 22

据我所知,reduce函数的知识(还不够)是Array.reduce遍历这样的数组-它获取每个数组值,并将它们与另一个参数一起通过回调函数放置(称为累加器)).下一个数组值将使用相同的回调函数,但(最终)更改了累加器值.

So, according to my knowledge (which is not enough) of reduce function is that Array.reduce iterate through an array like this - it takes each of array values and puts them through callback function with another argument (lets call it accumulator). The next array value will undergo the same callback function, but with (eventually) changed accumulator value.

在上面的代码示例中使我感到困惑的是:

What confuses me in code example above is:

1)数组是功能列表[double,add5].

1) Array is list of functions [double, add5].

2)在第一次迭代中,composeB将接收参数:f =累加器(空值),g = double(函数).ComposeB应该返回emptyvalue(double(6))(或者可能不是吗?)

2) In first iteration, composeB will receive arguments: f=accumulator (empty value), g=double(function). ComposeB should return emptyvalue(double(6)) (or maybe not??)

我知道我想念什么,但是有人可以向我解释什么吗?

I know that I am missing something, but can someone explain me what?

推荐答案

reduce的文档说第一个参数是

The documentation for reduce says that the first argument is

在数组中的每个元素上执行的函数(第一个元素除外,如果未提供initialValue的话).

A function to execute on each element in the array (except for the first, if no initialValue is supplied).

因此,在这种情况下,您没有提供 initialValue ,因此 compose 仅被调用一次(参数为 double add5 ).

So in this case, you have not supplied an initialValue and so compose is only called once (with arguments double and add5).

这篇关于Array.reduce如何将函数作为参数放入函数组合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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