简体   繁体   中英

Parameters inside callback function in Javascript

Lets consider forEach method of Javascript:

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

friends.forEach(function (eachName, index){
  console.log(index + 1 + ". " + eachName);
});

Can somebody please explain from where do the params eachName and index come from, since they were not defined anywhere in the code.

I understand it may quite obvious to many people but I am not not able to grasp this concept.

You should read the documentation on forEach. The function declared in forEach is called for every element in the array. forEach will call the inner function with the value of the array item as the first function parameter and the index of the array alement as the second function parameter.

So forEach will iterate over the array, similar to a for loop, and for every item in the array it will take the value and the index and pass it to the declared function.

Your confusion most likely come from the parameter names, but those names can be anything. The first parameter will always be the current item array value and the second the index.

To write your own function you would create a for loop that calls the defined function.

If we look at your original code and pull out the function (this is good for testing BTW).

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

function doStuff(eachName, index){
  console.log(index + 1 + ". " + eachName);
}    

// Does is still the same as yours
friends.forEach(doStuff);

// This loop does exactly what a forEach polyfill would do
for(var i = 0; i < friends.length; i++) {
    doStuff(a[i], i);
}

Have a look at the MDN foreach polyfill for a complete example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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