In the 链接到 MDN根据您提供的内容,您会找到答案:
三个参数(currentValue, index, array
) 是回调函数的参数 (arr.forEach(callback[, thisArg]
)。要在您的示例中显示它:
var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.forEach(function (currentValue, index){
console.log(index + 1 + ". " + currentValue);
});
所以当 forEach 运行时,会发生很多事情(查看 MDN 页面上的 polyfill),但在某些时候,forEach 将循环遍历数组中的项目并使用上面提到的参数调用您提供的回调。一个简化的版本是:
Array.prototype.forEach = function(callback, thisArg) {
// ...
for(let i = 0; let i < this.length; i++) { // "this" refers to your array here
// Here the arguments are passend in:
// currentValue = this[i]
// index = i
// array = this
callback.call(thisArg, this[i], i, this);
}
// ...
};