我正在研究 Javascript 回调和其他东西。我遇到了 forEach() 函数。 functioname 说明了一切,遍历列表中的每个对象。
当我查看 documentation 时我看到以下语法:
arr.forEach(callback[, thisArg])
而且文档中也提到了参数
currentValue
index
array
我偶然发现了一个简单的 forEach 实现示例:
var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName);
});
这给了我明显的输出:
"1. Mike"
"2. Stacy"
"3. Andy"
"4. Rick"
我可以接受所有行为及其给出的结果,但我想知道为什么这是有效的,我对此感到困惑
...function (eachName, index)...
何时何地或如何为每个名称和索引填充正确的值?或者我怎样才能看到 forEach 是如何实现的,因为我猜这个正在发挥作用?还是我在这里遗漏了一个重要的概念?
最佳答案
在link to 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 运行时,会发生很多事情(have a look at the polyfill on the MDN page),但在某些时候,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);
}
// ...
};
关于Javascript forEach 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369168/