简体   繁体   English

Javascript 如何匹配回调函数中的参数?

[英]How does Javascript match the parameters in a callback function?

I just started to learn JavaScript, and callback functions seem hard to understand.刚开始学JavaScript,回调函数好像不太懂。 One question I have is how javascript matches the parameters in a callback function?我的一个问题是 javascript 如何匹配回调函数中的参数? for example in the following forEach loop:例如在下面的 forEach 循环中:

 var friends = ['Mike', 'Stacy', 'Andy', 'Rick']; friends.forEach(function(eachName, index){ console.log(index + 1 + ". " + eachName); });

Is it by default that the forEach function will pass index to the second parameter and entry to the first parameter in the callback function?默认情况下,forEach 函数是否会将索引传递给回调函数中的第二个参数和第一个参数的入口?

In order to master callback functions, do I need to check the API (in this case, forEach) every time I use it?为了掌握回调函数,我每次使用它时是否都需要检查API(在这种情况下为forEach)?

Is it by default that the forEach function will pass index to the second parameter and entry to the first parameter in the callback function?默认情况下,forEach 函数是否会将索引传递给回调函数中的第二个参数和第一个参数的入口?

Yes;是的; this is part of the specification .这是规范的一部分 In fact, it also passes the array being iterated as the third argument.事实上,它还将被迭代的数组作为第三个参数传递。

Call the [[Call]] internal method of callbackfn with T as the this value and argument list containing [the value], [the index], and [the object] .使用 T 作为 this 值和包含 [值]、[索引] 和 [对象] 的参数列表调用 callbackfn 的 [[Call]] 内部方法。

(Emphasis mine.) (强调我的。)

In order to master callback functions, do I need to check the API (in this case, forEach) every time I use it?为了掌握回调函数,我每次使用它时是否都需要检查API(在这种情况下为forEach)?

Well, they're pretty consistent with each other, so you'll remember at some point.嗯,它们彼此非常一致,所以你会在某个时候记住。 map , filter , every , and some also work in this way. mapfiltereverysome也以这种方式工作。

Ya it's by default.To start using a function better if you refer some API.是的,默认情况下。如果您参考某些 API,则可以更好地开始使用功能。

I have used MDN for that.我为此使用了MDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM