JavaScript中forEach回调函数的第三个参数是什么? [英] What is point of third parameter in forEach callback function in JavaScript
本文介绍了JavaScript中forEach回调函数的第三个参数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道JavaScript中的 forEach 使用三个参数调用我的回调函数:
I know that forEach in JavaScript calls my callback function with three parameters:
arr.forEach(function callback(currentValue, index, array) {
//your iterator
})
在上面的例子中 arr
和数组
是相同的数组,回调函数闭包中存在 arr
。
In the above example arr
and array
are same array and arr
exists in the callback function closure.
现在问题是将数组
传递给回调函数是什么意思?
Now the question is what is the point of passing array
to the callback function?
推荐答案
如果您的回调函数在其他地方声明:
If your callback function were declared elsewhere:
function forEachCallback(value, i, array) {
// ...
}
然后它不知道它用于什么数组:
Then it has no idea what array it's being used for:
someArray.forEach(forEachCallback);
因为数组是作为最后一个参数传递,所以这样的回调有访问它。
Because the array is passed as the last argument, such a callback has access to it.
这篇关于JavaScript中forEach回调函数的第三个参数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文