简体   繁体   English

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

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

I've encountered with this piece of code in a book I'm reading, and I couldn't understand what the b argument that is defined in the function inside the forEach method does.我在我正在阅读的一本书中遇到过这段代码,我无法理解在 forEach 方法中的函数中定义的 b 参数是做什么的。

Here's the source code:这是源代码:

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

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

Okay, I've dug a bit deeper and found out that the function inside the forEach() method can take up to 3 arguments, so the function can be written like this: forEach(function(a, b, c) { // Instructions });好吧,我挖得更深一些,发现forEach()方法内部的函数最多可以接受 3 个参数,所以函数可以这样写: forEach(function(a, b, c) { // Instructions }); with a being the element of the current iteration, b being the index of that element and c being the array itself. a是当前迭代的元素, b是该元素的索引, c是数组本身。

Example:例子:

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

In this example, on the first iteration, a will be 'sample_1' b will be 0 and c will be the whole array.在这个例子中,在第一次迭代中, a将是 'sample_1' b将是 0 而c将是整个数组。 Second iteration, a is 'sample_2', b will be 1 and c will be the whole array.第二次迭代, a是 'sample_2', b是 1, c是整个数组。 And so on with all the remaining iterations.依此类推所有剩余的迭代。 Note that the function inside the forEach() method takes only 3 arguments, not more.请注意, forEach()方法中的函数只接受 3 个参数,而不是更多。

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

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