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

假装没事ソ 提交于 2019-12-18 06:56:14

问题


Javascript's array iteration functions (forEach, every, some etc.) allow you to pass three arguments: the current item, the current index and the array being operated on.

My question is: what benefits are there to operating on the array as an argument, vs. accessing it via the closure?

Why should I use this:

myArray.forEach(function(item, i, arr) {doSomething(arr);});

Instead of this:

myArray.forEach(function(item, i) {doSomething(myArray);});

回答1:


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) {});


来源:https://stackoverflow.com/questions/39528571/why-provide-an-array-argument-in-javascripts-array-foreach-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!