Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in javascript, declare more than one variable in for loop

have the following javascript code

// note: declaring i in this loop
for( var i=0; i<args.length; i++ ) {

   var elem = args[i];
   ...

   if( elem.attr == 'class' ) {

        // note declaring arr and i in this loop
        for( var arr=elem.val.split(' '), i=0; i<arr.length; i++ ) {

            element.classList.add(arr[classCt]);
        }
        continue;
    }
}

the problem is that i in the second for loop is the same i as declared in the first for loop.

thought that the var construct allowed multiple variables to be declared separated by commas.

when changed i to classCt in second loop, the code worked as expected

like image 730
cc young Avatar asked Feb 21 '23 02:02

cc young


2 Answers

You only have one scope there, so there can only be one variable with the same name. You're correct that var allows multiple variables to be declared separated by commas, but you can't declare two different variables with the same name in the same scope. You're just redeclaring a variable that already exists.

Either change it to classCt, or do what I do and use the variable j (and so on) for nested loop iterators:

var i, j, k, l;
for(i = 0; i < 10; i++){
    for(j = 0; j < 10; j++){
        for(k = 0; k < 10; k++){
            for(l = 0; l < 10; l++){
            }
        }
    }
}
like image 108
Paul Avatar answered Feb 23 '23 16:02

Paul


You are only working within one scope, the loop does not create it's own even if you use the var keyword. You are just overwriting your i variable within your current functional scope, so for example this:

for (var i = 0; i < 10; i++) {
        for (var i = 5; i < 10; i++) {
            console.log(i);
        }
}

Will just print 5,6,7,8,9.

If you want to create a new scope you would have to do it using functions as is typically done in javascript:

for (var i = 0; i < 10; i++) {
    (function(i) {
        for (var i = 5; i < 10; i++) {
            console.log(i);
        }
    })(i)
}

This will print 5,6,7,8,9 on their own lines 10 times.

like image 33
Art Avatar answered Feb 23 '23 16:02

Art