How does Javascript match the parameters in the callback function?

自古美人都是妖i 提交于 2019-12-31 04:28:07

问题


I just started to learn Javascript, and callback functions seem hard to understand. One question I have is how javascript matches the parameters in a callback function? for example in the following forEach loop:

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?

In order to master callback functions, do I need to check the API (in this case, forEach) every time I use it?


回答1:


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?

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].

(Emphasis mine.)

In order to master callback functions, do I need to check the API (in this case, forEach) every time I use it?

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.




回答2:


Ya it's by default.To start using a function better if you refer some API.

I have used MDN for that.



来源:https://stackoverflow.com/questions/24422764/how-does-javascript-match-the-parameters-in-the-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!