2

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;
}
3
  • variable total is not declared Commented Feb 11, 2015 at 13:57
  • You probably want to use idx < input in your for loop Commented Feb 11, 2015 at 13:58
  • thanks, yeah changing the <= to = seems to help Commented Feb 11, 2015 at 14:01

6 Answers 6

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

nice functional style - not very newbie-friendly, though.
2

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;
}

Comments

1

variable total is not declared!

function sum(input) {
    var total = 0;
    for (idx=0; idx <= input.length; idx++) {
        total += input[idx];
    }
    return total;
}

1 Comment

It seems declared to me. Only it's global, so the results will always grow.
0

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 )....

2 Comments

ahh thanks very much .. thats where i was going wrong .. this has sorted it now thanks very much
@dannywhite: be sure to take the other answers into account, too: your total is globally scoped.
0

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);

Comments

0

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.