简体   繁体   English

为什么在 Javascript 的 array.forEach 回调中提供一个数组参数?

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

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. Javascript 的数组迭代函数( forEacheverysome等)允许您传递三个参数:当前项、当前索引和正在操作的数组。

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

It is possible that you want to pass a generic function as an argument to forEach and not an anonymous function.您可能希望将泛型函数作为参数传递给forEach而不是匿名函数。 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, eg:另一种可能有用的情况是,数组尚未存储在变量中,因此没有可引用的名称,例如:

[1, 2, 3].forEach(function(item, i, arr) {});

there is many cases in real life where knowing where an error is occuring and what was the content of your array.在现实生活中有很多情况知道错误发生在哪里以及数组的内容是什么。 And focusly in a backend JS context like a NodeJS application..并专注于后端 JS 上下文,如 NodeJS 应用程序..

Imagine your website is attacked, you want to know how your pirats are looking to enter into your website, in that case providing the array which contained the entire elements is useful.想象一下您的网站受到攻击,您想知道盗版者如何进入您的网站,在这种情况下,提供包含整个元素的数组很有用。 Look at the ECMASCRIPT 2020 page 642-643 it is written看ECMASCRIPT 2020 page 642-643 是这么写的

callbackfn is called with three arguments: 
the value of the element,
the index of the element,
and the object being traversed

illustration :插图: callbackfn 使用三个参数调用:元素的值、元素的索引和被遍历的对象 Ecmascript 2020 手册

ok try this example好的试试这个例子

 let myArray = [2 , 3, 5 , 7 , "ഊമ്പി", 13] let foo = null myArray.forEach(function(value, index, currentObject) { try { foo = 3.14*value; if (Number.isNaN(foo)) throw "foo is NaN" } catch (error) { console.error(error + ", and value: " + value + ", index: " + index + ", currentObject: " + currentObject); } });

Hope that answer will help newbies That's all folk's !希望这个答案能帮助新手 这是所有人的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM