admin管理员组文章数量:1399823
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 mas.
when changed i
to classCt
in second loop, the code worked as expected
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 mas.
when changed i
to classCt
in second loop, the code worked as expected
- 1 "when changed i to classCt in second loop, the code worked as expected" - so why don't you just go with that? – Niko Commented Mar 18, 2012 at 1:53
-
Changed
i
toclassCt
where? Thei
in second for loop is indeed the same as the first because you are not initializing it again withvar
. – user201788 Commented Mar 18, 2012 at 1:55
2 Answers
Reset to default 7You 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 mas, 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++){
}
}
}
}
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.
本文标签: In JavaScriptdeclare more than one variable in for loopStack Overflow
版权声明:本文标题:in javascript, declare more than one variable in for loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741662808a2391140.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论