我刚开始学习JavaScript,回调函数似乎很难理解。我的一个问题是 javascript 如何匹配回调函数中的参数?例如在下面的 forEach 循环中:
var friends = ['Mike', 'Stacy', 'Andy', 'Rick'];
friends.forEach(function(eachName, index){
console.log(index + 1 + ". " + eachName);
});
forEach函数在回调函数中是否默认将index传给第二个参数,entry传给第一个参数?
为了掌握回调函数,我是否需要每次使用它时都检查 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?
是的; this is part of the specification .事实上,它还将被迭代的数组作为第三个参数传递。
Call the [[Call]] internal method of callbackfn with T as the this value and argument list containing [the value], [the index], and [the object].
(强调我的。)
In order to master callback functions, do I need to check the API (in this case, forEach) every time I use it?
好吧,它们彼此非常一致,所以你会在某个时候记住的。 map
、filter
、every
和 some
也以这种方式工作。
关于javascript - Javascript 如何匹配回调函数中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24422764/