JavaScript forEach的正确使用方法

3

我无法清晰地理解 JavaScript 中 forEach() 的参数用法。(我了解第一个参数是将在数组的每个元素上调用的函数。) 这是我的问题:

1) 第二个参数是用来干什么的?有人能举个例子吗?
2) 函数 (第一个参数) 总是有三个参数:entry、index 和 array 吗?
3) 有些网站解释 Array.prototype.forEach(),这是相同的 forEach() 还是不同的东西?

这是我的jsfiddle

我尝试在网上搜索简单的解释,但徒劳无功!感谢您的帮助。

2个回答

3
  1. The second argument is used to set this in the function context. An example:

    var person = {
        name: 'Bob',
        age: 30
    };
    
    var arr = ["foo", "moo", "koo"];
    
    arr.forEach(function(entry, index, array) {
        console.log(this.name + ' says ' + entry);
    }, person);
    
  2. You will always get all 3 of those, but you don't need to reference them if you don't need them.

  3. They are the same.

感谢你的解释! - rgamber

0

1) forEach的第二个参数允许你控制函数内部传入的'this'变量,该函数是作为forEach的第一个参数传入的。

2) 你的函数总是会传入这三个参数,但如果你只需要前两个参数或者第一个参数,你可以定义你的函数来接收它们。

3) 是的,当人们谈论forEach时,他们实际上是在引用Array.prototype.forEach()。(在你的jsfiddle中,你正在对一个数组对象调用forEach)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接