Why provide an array argument in Javascript's array.forEach callback?

后端 未结 1 691
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 07:46

Javascript\'s array iteration functions (forEach, every, some etc.) allow you to pass three arguments: the current item, the current i

相关标签:
1条回答
  • 2020-12-19 08:28

    It is possible that you want to pass a generic function as an argument to forEach and not an anonymous function. Imagine a situation where you have a function defined like that:

    function my_function(item, i, arr) {
        // do some stuff here
    }
    

    and then use it on different arrays:

    arr1.forEach(my_function);
    arr2.forEach(my_function);
    

    The third argument allows the function to know which array is operating on.

    Another case where this might be usefull, is when the array has not been stored in a variable and therefore does not have a name to be referenced with, e.g.:

    [1, 2, 3].forEach(function(item, i, arr) {});
    
    0 讨论(0)
提交回复
热议问题