JavaScript 的 forEach 方法以一个函数作为参数,该函数接受一个似乎没有作用的参数

JavaScript's forEach method taking a function as a parameter that takes an argument that seems it has no role

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

这是源代码:

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

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

好吧,我挖得更深一点,发现 forEach() 方法里面的函数最多可以接受 3 个参数,所以函数可以这样写: forEach(function(a, b, c) { // Instructions }); with 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 个参数,而不是更多。