Understanding Eloquent Javascript's Reduce function

前端 未结 3 1489
长发绾君心
长发绾君心 2020-12-29 18:00

In Eloquent Javascript, the author asks the reader to write a function countZeroes, which takes an array of numbers as its argument and returns the amo

3条回答
  •  粉色の甜心
    2020-12-29 18:27

    the function counter is passed as the first parameter of reduce when called in your first block of code. Within the reduce function, the first parameter is known as combine. This is then called with parameters base and element which are the mysterious arguments you are seeking!

    So the tricky bit, is that the function is not executed where it is defined and named, but passed as a parameter to the reduce function, which then executes it.

    Edit: elaboration

    logic flow

    so... the function is defined and named (at point 1), then the definition is passed, without the name to another function (at point 2) along with variables (I called i and ii) where it picks up the name of the first parameter (at point 3) before being called (at point 4) along with the other parameters

    edit: further elaboration

    I updated the image, to better explain the elements coming from the array.

    So i is easier to follow, being created as 0 when the reduce function is called, and allocated the name base as a parameter, before being reassigned as the result of the counter/combine function, which returns the base with a possible increment.

    ii starts life as an array passed to countZeroes, and is then passed along the chain until it is iterated over by a forEach loop, which extracts a single element and operates the combine function on it (along with base).

提交回复
热议问题