问题描述
Javascript的数组迭代函数( forEach
,每个
,一些
等)允许你传递三个参数:当前项目,当前索引和正在操作的数组。
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?
我为什么要使用它:
myArray.forEach(function(item, i, arr) {doSomething(arr);});
而不是:
myArray.forEach(function(item, i) {doSomething(myArray);});
推荐答案
您可能希望传递通用函数作为 forEach
的参数,而不是匿名函数。想象一下你有一个像这样定义的函数的情况:
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) {});
这篇关于为什么在Javascript的array.forEach回调中提供数组参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!