繁体   English   中英

回调函数的arguments是如何工作的?

[英]How do the arguments of callback functions work?

我刚从 javascript 开始,我无法真正理解回调函数是如何工作的。 这听起来可能很愚蠢,但我有一些问题。 不合适我就删了

If a callback function is a function passed as an argument to another function, what happens to the arguments of the callback function?

是否会使用回调 function 执行两次(一次用作参数时,另一次在声明时)?

此外,我无法理解在回调 function arguments 下方附加的照片中如何获取数组中元素的值。

在此处输入图像描述

通过以您的代码片段为例,我们看到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.

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