JavaScript中的回调函数内部的参数 [英] Parameters inside callback function in Javascript

查看:55
本文介绍了JavaScript中的回调函数内部的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一下Java的forEach方法:

Lets consider forEach method of Javascript:

var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (eachName, index){
  console.log(index + 1 + ". " + eachName);
});

有人可以解释一下每个名称和索引的参数来自何处,因为它们没有在代码中的任何地方定义.

Can somebody please explain from where do the params eachName and index come from, since they were not defined anywhere in the code.

我知道这对很多人来说可能是很明显的,但是我不能理解这个概念.

I understand it may quite obvious to many people but I am not not able to grasp this concept.

推荐答案

您应该阅读forEach上的文档.对于数组中的每个元素,都会调用forEach中声明的函数.forEach将使用数组项的值作为第一个函数参数并使用数组alement的索引作为第二个函数参数调用内部函数.

You should read the documentation on forEach. The function declared in forEach is called for every element in the array. forEach will call the inner function with the value of the array item as the first function parameter and the index of the array alement as the second function parameter.

因此forEach将遍历数组,类似于for循环,并且对于数组中的每个项目,它将获取值和索引并将其传递给声明的函数.

So forEach will iterate over the array, similar to a for loop, and for every item in the array it will take the value and the index and pass it to the declared function.

您的困惑很可能来自参数名称,但是这些名称可以是任何名称.第一个参数将始终是当前项目数组的值,第二个参数将是索引.

Your confusion most likely come from the parameter names, but those names can be anything. The first parameter will always be the current item array value and the second the index.

要编写自己的函数,您需要创建一个for循环,以调用已定义的函数.

To write your own function you would create a for loop that calls the defined function.

如果我们查看您的原始代码并提取该功能(这对测试BTW很有用)

If we look at your original code and pull out the function (this is good for testing BTW).

var friends = ["Mike", "Stacy", "Andy", "Rick"];

function doStuff(eachName, index){
  console.log(index + 1 + ". " + eachName);
}    

// Does is still the same as yours
friends.forEach(doStuff);

// This loop does exactly what a forEach polyfill would do
for(var i = 0; i < friends.length; i++) {
    doStuff(a[i], i);
}

请查看每个polyfill的MDN以获取完整示例.

Have a look at the MDN foreach polyfill for a complete example.

这篇关于JavaScript中的回调函数内部的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆