I can't figure out how this works. Here's the code.
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);
I get that sum =+ number;
is getting passed to forEach
and looping through the array numbers. But I can't make out the details of how that happens. Putting function(number) {sum =+ number}
in place of action
like so
for (var i = 0; i < [1, 2, 3, 4, 5].length; i++)
function(number) {
sum += number;
} (array[i]);
}
doesn't make sense, nor does it run. What would work is
var numbers = [1, 2, 3, 4, 5], sum = 0;
for (var i = 0; i < numbers.length; i++)
sum += (numbers[i]);
debug(sum);
console.log(sum);
which is as much as I can compress it and make it work. But how do you get to here? In other words what's really happening?
Thanks for any help. This concept seems basic to Haverbeke's approach, so I think I'd better understand it.