简体   繁体   English

在javascript中,在for循环中声明多个变量

[英]in javascript, declare more than one variable in for loop

have the following javascript code 有以下javascript代码

// 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. 问题是, i在第二for循环是相同i在第一声明for环路。

thought that the var construct allowed multiple variables to be declared separated by commas. 认为var构造允许用逗号分隔多个变量。

when changed i to classCt in second loop, the code worked as expected 当在第二个循环classCt i更改为classCt时,代码按预期工作

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. 你是正确的,var允许用逗号分隔多个变量,但你不能在同一范围内声明两个具有相同名称的不同变量。 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: 将其更改为classCt ,或者执行我的操作并将变量j (依此类推)用于嵌套循环迭代器:

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++){
            }
        }
    }
}

You are only working within one scope, the loop does not create it's own even if you use the var keyword. 您只在一个范围内工作,即使您使用var关键字,循环也不会创建它自己。 You are just overwriting your i variable within your current functional scope, so for example this: 您只是在当前功能范围内覆盖您的i变量,例如:

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. 将只打印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: 如果你想创建一个新的范围,你必须使用通常在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. 这将在他们自己的线上打印5,6,7,8,9 10次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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