[英]How do the arguments of callback functions work?
通过以您的代码片段为例,我们看到logPerson
是 function。 此外,我们正在使用Array.prototype.forEach
循环遍历people
数组。
现在 forEach 将 function 作为参数,它使用 arguments 作为每次迭代的项目值和索引来调用它。
因此,当我们将logPerson
作为参数传递给forEach
时,这个 function 会被 forEach 传递给其回调的 arguments 调用
forEach 的一个简单实现可能是
Array.prototype.forEach = function(callback) {
const arr = this;
for(let i = 0; i < arr.length; i++) {
callback(arr[i], i);
}
}
编写示例的另一种方法是
let people = ["mario", "luigi", "rui"];
people.forEach((person, index) => {
console.log(`${index} - hello ${person}`);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.