0

I'm new at coding and am trying to figure out why this doesn't work. the function works fine I'm assuming there is a fundamental flaw in the sumArray function that is not processing

// SET UP FUNCTIONS FOR LATER USE   

// sumArray - takes all values within an array and adds them 
var sumArray = function(x){
    var sum = 0;
    for(i=0;i<x.length;i++) {
        sum += parseInt(x[i]);
    };
    return sum;     
};

// create an array and use sumArray function inside of a loop.

// This works
var arrayTest = new Array(1,2,3,4,5,6,7,8,9,10);
document.write (sumArray(arrayTest);

// This crashes the browser
for(i=0;i<10;i++){
document.write("<br/>" + sumArray(arrayTest) + "<br/>"); 
};

Thanks in advance for any insight.

4
  • 2
    You should [1, 2, 3 ...] instead of new Array(1, 2, 3 ... ) Commented Oct 5, 2012 at 17:20
  • Missing closing parenthesis in document.write(sumArray... Commented Oct 5, 2012 at 17:20
  • The term "crash the browser" means that the entire browser process fails. Is that what's happening? Commented Oct 5, 2012 at 17:22
  • And you should accept both answers, which will crash not only your browser, but will cause the whole universe collapse. ;-) Commented Oct 5, 2012 at 17:22

2 Answers 2

4

You need to declare "i" with var:

for(var i=0;i<10;i++){

in both loops. If you don't do that, there's just one global "i" clobbered by both loops.

Sign up to request clarification or add additional context in comments.

3 Comments

It won't "crash the browser" in this case but it will make thinks work incorrectly.
Well, nothing should "crash the browser" short of browser bug.
Yeah, I guess it would only cause the main loop to run only once, but certainly needs to be fixed.
4

Just before the second loop, you're missing a ).

document.write (sumArray(arrayTest) ); // <-- right here

Additionally, be very careful with document.write. If it runs while the document is loading, you'll probably be alright. Be sure you don't use it after the doc has loaded.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.