iterate over an array and sum up all values with JS
10,595
Solution 1
You are using input
both as an integer, and as an array of values. Probably you mean for( var idx = 0; idx < input.length; ++idx )...
.
Solution 2
You actually don't need a loop to do this in modern browsers, you can use the Array.reduce function:
var sum = input.reduce(function(a,b){
return a+b;
}, 0);
Solution 3
variable total is not declared!
function sum(input) {
var total = 0;
for (idx=0; idx <= input.length; idx++) {
total += input[idx];
}
return total;
}
Author by
danny white
Updated on June 13, 2022Comments
-
danny white almost 2 years
as the title says i'm trying to sum up using a for loop to iterate over an array. can you give me some pointers as to where i'm going wrong here. i am returning the value NaN.
var total = 0; function sum(input) { for (idx=0; idx<=input; idx++) { total += input[idx]; } return total; }
-
xtofl about 9 yearsIt seems declared to me. Only it's global, so the results will always grow.
-
danny white about 9 yearsahh thanks very much .. thats where i was going wrong .. this has sorted it now thanks very much
-
xtofl about 9 yearsnice functional style - not very newbie-friendly, though.
-
xtofl about 9 years@dannywhite: be sure to take the other answers into account, too: your
total
is globally scoped.