【问题标题】:Why provide an array argument in Javascript's array.forEach callback?为什么在 Javascript 的 array.forEach 回调中提供一个数组参数?
【发布时间】:2017-01-24 12:15:20
【问题描述】:

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

我的问题是:将数组作为参数进行操作与通过闭包访问它有什么好处?

我为什么要使用这个:

myArray.forEach(function(item, i, arr) {doSomething(arr);});

而不是这个:

myArray.forEach(function(item, i) {doSomething(myArray);});

【问题讨论】:

  • 如果你想传递数组作为参数,为什么要把它包装在.forEach中?

标签: javascript arrays closures


【解决方案1】:

您可能希望将通用函数作为参数传递给forEach,而不是匿名函数。想象一下你有一个这样定义的函数的情况:

function my_function(item, i, arr) {
    // do some stuff here
}

然后在不同的数组上使用它:

arr1.forEach(my_function);
arr2.forEach(my_function);

第三个参数允许函数知道哪个数组正在操作。

这可能有用的另一种情况是数组没有存储在变量中,因此没有要引用的名称,例如:

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

【讨论】:

    【解决方案2】:

    在现实生活中有很多情况下知道错误发生在哪里以及数组的内容是什么。并专注于后端 JS 上下文,如 NodeJS 应用程序..

    假设您的网站受到攻击,您想知道盗版者希望如何进入您的网站,在这种情况下,提供包含整个元素的数组很有用。看看 ECMASCRIPT 2020 第 642-643 页是这样写的

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

    插图:

    好的,试试这个例子

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

    希望这个答案对新手有所帮助 都是人家的!

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 2013-12-01
      • 1970-01-01
      • 2022-12-17
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      相关资源
      最近更新 更多