JavaScript 中 forEach 回调函数中第三个参数的点是什么 [英] What is point of third parameter in forEach callback function in JavaScript

查看:51
本文介绍了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
})

在上面的例子中arrarray是同一个数组,arr存在于回调函数闭包中.

In the above example arr and array are same array and arr exists in the callback function closure.

现在的问题是将array传递给回调函数有什么意义?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆