为什么在 Javascript 的 array.forEach 回调中提供一个数组参数? [英] Why provide an array argument in Javascript's array.forEach callback?

查看:40
本文介绍了为什么在 Javascript 的 array.forEach 回调中提供一个数组参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript 的数组迭代函数(forEacheverysome 等)允许你传递三个参数:当前项、当前项索引和正在操作的数组.

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 回调中提供一个数组参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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