Created
June 13, 2013 19:16
-
-
Save gavinblair/5776514 to your computer and use it in GitHub Desktop.
I have a bunch of loops, for different arrays. I just need some counters. When I do this, jshint says my variables k and l are already defined. Should I move on to other letters of the alphabet? Is there a better way?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for(var k in myarray){ | |
for(var l in myarray[k]){ | |
//do something with myarray[k][l] | |
} | |
} | |
for(var k in someotherarray){ | |
for(var l in someotherarray[k]){ | |
//do something with someotherarray[k][l] | |
} | |
} |
You can use function scoping. This gives an additional overhead of a closure, with attending allocations and deallocations, but it's quick and dirty, and a more universal solution that the resetting solution @SeanJA gives.
(function(){
for(var k in something) {
// ...
}
})();
(function(){
for(var k in somethingElse) {
// ...
}
})();
However, it's arguably better to just use variable names that have more meaning... somethingIdx
, somethingElseIdx
for instance. Or simply resetting. :)
You're over-thinking it, you just can't declare the variable every time:
var k;
var l;
for(k in myarray){
for(l in myarray[k]){
//do something with myarray[k][l]
}
}
for(k in someotherarray){
for(l in someotherarray[k]){
//do something with someotherarray[k][l]
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why not that? Note, I didn't put it through jslint (also, you should try
jshint
instead ofjslint
, it is less mean).jshint report for:
JSHint Report: