Javascript forEach 回调

标签 javascript foreach

我正在研究 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/

相关文章:

jsf - 在 JSF 中迭代,使用 for 每个循环渲染纯 HTML <div> 元素

php - explode 和 foreach 问题

javascript - 搜索过滤器继续搜索所有类别 Jquery

php - 如何使用 foreach PHP 循环 3 维数组

javascript - 从javascript数组中提取具有唯一字符的字符串

javascript - ASP.NET MVC 捆绑子文件夹结构

javascript - 智能数组过滤JS

ASP.NET Ajax : close window after Ajax call?

javascript - 错误 : Text content does not match server-rendered HTML

javascript - 如何用 mithril 等价物替换 jquery?