简体   繁体   中英

javascript function in a for loop not causing crashing browser

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM