In javascript, declare more than one variable in a 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 in the first for loop.

I thought that the var construct allows the declaration of several variables, separated by commas.

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

+4
source share
2 answers

You have only one scope, so there can only be one variable with the same name. You are correct that var allows you to declare multiple variables separated by commas, but you cannot declare two different variables with the same name in the same scope. You are simply updating a variable that already exists.

Either change it to classCt , or do what I do and use the j variable (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++){ } } } } 
+7
source

You work only within one scope; the loop does not create it, even if you use the var keyword. You simply overwrite your I variable in your current functional area, for example, for example:

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

It will just print 5,6,7,8,9.

If you want to create a new scope, you will need to do this using functions, as is usually 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 its lines 10 times.

+1
source

Source: https://habr.com/ru/post/1402050/


All Articles