Reputation: 615
I have an exercise where I have to write my own forEach function which takes an array and a 'callback' function to add all the elements in the array. So far I have this:
function forEachTest(arr, func){
func(arr) // Simply apply the function to the array
}
However I don't know if this is the correct way a forEach call works.
Secondly, the said function to add the elements will therefore take the array and somehow add each element one by one till it reaches the end of the array and then console.log(result).
I tried using a variable to store the value but this doesn't work, I get NaN as a result.
function addEach(arr) {
var sum;
for(i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log(sum);
}
The Nan happens when I call forEachTest(arr, addEach);
Note that arr is any array containing numbers.
Upvotes: 0
Views: 143
Reputation: 38502
What about this with initialization of your sum
variable with 0
because inside your function it is initially undefined
. So inside your loop it is executing like this way
undefined=undefined+1
, undefined=undefined+2
and so on which is NaN
for every number of your array. Also I guess you're missing the return
before your func(arr);
function forEachTest(arr, func){
return func(arr) // Simply apply the function to the array
}
function addEach(arr) {
var sum=0;// see here
for(i = 0; i < arr.length; i++) {
sum += arr[i];
//console.log(sum += arr[i]) //for debug purpose
}
//console.log(sum);
return sum;
}
console.log(forEachTest([1,2,3,4,5],addEach))
Upvotes: 0
Reputation: 33726
Initialize the variable sum = 0
.
function forEachTest(arr, func) {
func(arr);
}
function addEach(arr) {
var sum = 0;
for (i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log(sum);
}
forEachTest([1,2,3], addEach);
Upvotes: 2