简体   繁体   English

回调函数的参数如何工作?

[英]How callback function's parameters work?

So I'm trying to understand functional programming and higher order functions in specific. 因此,我尝试着具体地理解函数式编程和高阶函数。 What I never clearly understood, was how callback function's parameters have a connection to, for example, an array? 我从未清楚地了解过,回调函数的参数如何与例如数组建立联系?

To be more clear, let's take this code example: 更清楚地说,让我们看下面的代码示例:

var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick
});

How a callback parameter eachName knows that it means to return the item from array and index is supposed to return an index of array? 回调参数eachName如何知道它意味着要从数组返回项目,而index应该返回数组的索引? How the connection between an array and callback parameter works? 数组和回调参数之间的连接如何工作?

the forEach method is calling or invoking your callback function. forEach方法正在调用或调用您的回调函数。 To be more specific let's see how the forEach work. 更具体地说,让我们看看forEach的工作方式。

function forEach(arr, func) {
  for (var i = 0; i < arr.length; i++) {
    func(arr[i], i);
  }
}

Now you can do something like this. 现在,您可以执行类似的操作。

 function forEach(arr, func) { for (var i = 0; i < arr.length; i++) { func(arr[i], i); } } var cars = ["BMW", "Tata Nano", "Lamborghini"]; forEach(cars, function (car, index) { alert(car + " " + index); }); 

The API does it for you. API为您完成。 In this case, array.forEach 's callback is always set to accept 3 arguments: the current item, the current item's index in the array, and the array itself. 在这种情况下, array.forEach的回调始终设置为接受3个参数:当前项,当前项在数组中的索引以及数组本身。

One example of an API that has a different argument signature is array.reduce . 具有不同参数签名的API的一个示例是array.reduce It is set to accept 4 arguments: The accumulator, the current item, the current item's index and the array itself. 它设置为接受4个参数:累加器,当前项目,当前项目的索引和数组本身。

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

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