Warning: Duplicate Variable Definition

If I have 2 for

, loops declaring var i

, then the second will throw 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 for this, he explained in this answer , but is there a way to get around this (other than the declaration i

at the beginning of the method)?

+3


source to share


2 answers


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 without error - since your warning tells you that it is already defined, so you can use it again by setting it back to 0 to ensure that the loop runs correctly.

+3


source


If you are as adamant about using a loop as you are using, consider wrapping 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       
        } 
    })();
}

      



While it didn't give any warning, I wonder what purpose this would actually solve for you.

+1


source







All Articles