简体   繁体   中英

Higher-Order Functions in JS

I'm learning JavaScript now. And I have some question. The following code from the book Eloquent JavaScript:

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

var numbers = [1, 2, 3, 4, 5],
    sum = 0;

forEach(numbers, function(number) {
    sum += number;
});

console.log(sum); 

What is happening in this code? How does the forEach function, when called, determine what is the number? How does it extract number from the numbers array?

What is happening in this code?

Here's a description of how your forEach function works:

  1. Your forEach function accepts two arguments, the array and a function
  2. It sets up a for loop to iterate through the array
  3. Then, for each element in the array it calls action(array[i]) which calls the passed in function and passes it one array element. array[i] gets the next item from the array and action(array[i]) calls the passed in function and passes it that next item from the array.

Then, when you call it like this:

forEach(numbers, function(number) {
    sum += number;
});

It will call the function you passed it once for each number in the numbers array and when it calls that function, it passed a number from the array as the first argument to your function.

One thing that confuses some people is the number argument in your function you are passing to forEach is just a name you assign to the first argument of the function. It can be named anything you want and has nothing to do with any names used in the forEach() function definition. The declaration of arguments for functions are just labels assigned to each argument which make it easier for you to use them. You could have also done this:

forEach(numbers, function(whateverYouWant) {
    sum += whateverYouWant;
});

How does the forEach function, when called, determine what is the number?

Your for loop iterates through the whole array one number at a time and calls the callback function once for each number in the array.

How does it extract number from the numbers array?

array[i] is where a number is extracted from the array. This is normal array indexing for retrieving the i th value from the array where i varies from 0 to the length of the array minus 1.

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