Reputation: 51
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;
}
Upvotes: 2
Views: 15543
Reputation: 20254
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);
Upvotes: 7
Reputation:
You need ot declare total into function and also you need to declare idx. Another thing that instead of writing idx <= input.length
you have to write idx <= input.length - 1
. Since last index will be undefined.
Try
function sum(input) {
total = 0;
for (var idx = 0; idx <= input.length - 1; idx++) {
total += input[idx];
}
return total;
}
Upvotes: 2
Reputation: 41519
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 )...
.
Upvotes: 0
Reputation: 529
Declare the variable total inside the function, and also use input.length-1 to define the loop's range:
function sum(input) {
var total = 0;
for (idx=0; idx <= input.length-1; idx++) {
total += input[idx];
}
return total;
}
Upvotes: 0
Reputation: 1442
Problem which result in NaN
is because of your array traversing array till end, rather than from indices 0
to input.length-1
Try this:
http://jsfiddle.net/t9tfofxv/
var total = 0;
function sum(input) {
for (var idx=0; idx< input.length; idx++) {
total += input[idx];
}
return total;
}
var s=sum([1,2,3,4]);
alert(s);
Upvotes: 0
Reputation: 4076
variable total is not declared!
function sum(input) {
var total = 0;
for (idx=0; idx <= input.length; idx++) {
total += input[idx];
}
return total;
}
Upvotes: 1