Javascript function as a parameter to another function?

后端 未结 7 1102
执念已碎
执念已碎 2021-01-31 06:17

I\'m learning lots of javascript these days, and one of the things I\'m not quite understanding is passing functions as parameters to other functions. I get the concept

7条回答
  •  春和景丽
    2021-01-31 06:30

    One of the most common usages is as a callback. For example, take a function that runs a function against every item in an array and re-assigns the result to the array item. This requires that the function call the user's function for every item, which is impossible unless it has the function passed to it.

    Here is the code for such a function:

    function map(arr, func) {
        for (var i = 0; i < arr.length; ++i) {
            arr[i] = func(arr[i]);
        }
    }
    

    An example of usage would be to multiply every item in an array by 2:

    var numbers = [1, 2, 3, 4, 5];
    map(numbers, function(v) {
        return v * 2;
    });
    
    // numbers now contains 2, 4, 6, 8, 10
    

提交回复
热议问题