If I have 2 for loops both declaring var i, then the second will produce a warning:
public function twoLoops(){
for (var i:int = 0; i < 100; i++) {
}
for (var i:int = 0; i < 100; i++) { // i is already declared once
}
}
I understand the reason this happens, it's explained in this answer, but is there a way around it (except for declaring i at the beginning of the method)?
It's simple - just don't declare it in the second loop:
public function twoLoops(){
for (var i:int = 0; i < 100; i++) {
}
for (i = 0; i < 100; i++) { // i is already declared once
}
}
This will work with no error - as your warning tells you, it's already defined, so you can use it again, setting it back to 0 to allow the loop to execute properly.
If you are so adamant in using the loop the way you are using, consider wrapping up in a function:
public function twoLoops() {
for (var i:int = 0; i < 10; i++) {
}
(function(){
for (var i:int = 0; i < 100; i++) { // i is already declared once
}
})();
}
Though it would not give any warning, I wonder what purpose would it really solve for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With