Reputation: 23
I am having trouble with for
loops and I cannot seem to figure this out. I need to add the numbers in an array. The closest I get is I get the loop to print the array 1,2,3 three times with this code
function sumArray(num) {
for (var i = 0; i < sumArray.length; i++) {
var total = 0;
console.log(num);
}
}
sumArray([1,2,3])
and when I use this code all it does is log 1
function sumArray(num) {
var total = 0;
for (var i = 0; i < sumArray.length; i++) {
console.log(total += num[i]);
}
}
sumArray([1,2,3])
At one point I got it to return undefined three times
Upvotes: 2
Views: 72
Reputation: 12209
Use Array.reduce()
:
function sumArray(arr) {
return arr.reduce((acc,curr) => acc + curr);
}
console.log(sumArray([1,2,3,4]));
Upvotes: 1
Reputation: 41893
Welcome at Stack Overflow :) First of all, your naming things is kind of misleading, since sumArray
argument is called num
(which suggest that it accepts just a number, not an array) - I would suggest you to name it e.g. arr
.
Secondly - remember about returning your total
variable when the for loop finishes.
Lastly - sumArray
is a function, then sumArray.length
will return 1
- which is the amount of how many arguments function expects - so actually your loop will fire only once.
function sumArray(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
console.log(sumArray([1, 2, 3]))
Upvotes: 1
Reputation: 78840
The problem is that you're looping over the wrong structure with this line:
for (var i = 0; i < sumArray.length; i++)
You want to loop over the num
parameter you passed in. sumArray
is the name of the function, and sumArray.length
is the number of parameters of the function. Do this instead:
function sumArray(num) {
var total = 0;
for (var i = 0; i < num.length; i++) {
console.log(total += num[i]);
}
}
You probably want to add a return total;
in there as well so that sumArray
returns the sum instead of just printing the running total as it loops.
Upvotes: 2