【问题标题】:JavaScript's forEach method taking a function as a parameter that takes an argument that seems it has no roleJavaScript 的 forEach 方法将一个函数作为参数,该参数接受一个似乎没有作用的参数
【发布时间】:2021-11-15 08:59:07
【问题描述】:

我在正在阅读的一本书中遇到过这段代码,我无法理解在 forEach 方法内部的函数中定义的 b 参数的作用。

这里是源代码:

var tab = [2, 3, 5];
tab.map(x => x + 3)
   .filter(x => x > 5)
   .forEach(function(a,b){console.log(a-3);});

【问题讨论】:

标签: javascript foreach


【解决方案1】:

b是可选的,它是元素的索引

【讨论】:

    【解决方案2】:

    好吧,我挖得更深了,发现forEach()方法里面的函数最多可以有3个参数,所以函数可以写成这样:forEach(function(a, b, c) { // Instructions });其中a是元素在当前迭代中,b 是该元素的索引,c 是数组本身。

    例子:

    const samples = ['sample_1', 'sample_2', 'sample_3'];
    samples.forEach(function(a, b, c){
        console.log(a); // shows the element
        console.log(b); // shows the index of the element
        console.log(c); // shows the whole array
        console.log('Onto the next sample.')
    });
    

    在此示例中,在第一次迭代中,a 将是“sample_1”b 将是 0,c 将是整个数组。 第二次迭代,a 是 'sample_2',b 将是 1,c 将是整个数组。 等等所有剩余的迭代。请注意,forEach() 方法中的函数只需要 3 个参数,而不是更多。

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多