Higher order functions - Javascript

前端 未结 2 1734
清歌不尽
清歌不尽 2021-01-22 10:21

I am working through Eloquent Javascript. The function count takes an array and a test function (equals(x)) as arguments, and returns the amount of elements in

2条回答
  •  没有蜡笔的小新
    2021-01-22 11:10

    The 3 arguments you passed to reduce were:

    {
        combine:function(total, element){...},
        base:0,
        array:array
    }
    

    The function then takes base and passes it to the combine function as the total argument:

    base = combine(base, element);
    

    Basically, what is happening here is that for each element in the array you just passed (as the 3rd argument array) the function takes the argument base and increments it using the anonymous function you have provided (which first checks if the element passes test). Finally, after it has iterated over all the elements, it returns the final value of base.

    Perhaps this will help explain:

    function count(test, testarray) {
      var anon = function(total, element) { // Where is the value for total coming from?
        return total + (test(element) ? 1 : 0);
      };
      //now anon is a function.
      return reduce(anon, 0, testarray);
    }
    

    Let us look at the function invocation and definition closely:

    return   reduce(anon   , 0   , testarray);
                      |      |     |
                      v      v     v
    function reduce(combine, base, array) {
        combine;    //the function that is passed in as the first argument
        base;       //the number that is passed in as the second argument
        array;      //the array that is passed in as the third argument
    

    The values of each of anon,0, and testarray, get passed into the function. Within the function, their values can be accessed by the parameter names in the function definition.

提交回复
热议问题