Dealing with duplicate declaration warning for loop variables

前端 未结 5 1853
傲寒
傲寒 2021-02-02 05:44

Consider the following code:

for (var i=0; i<100; i++) {
    // your code here
}
// some other code here
for (var i=0; i<500; i++) {
    // custom code her         


        
5条回答
  •  醉梦人生
    2021-02-02 06:30

    best practice here should be good programming style:

    A program should be constructed in short functions, which will do one little task. Usually, if you're looping, you do something such special which should stand in an own function. In the end every function has his own scope, so that the duplicate-declaration-problem is away.

    function myApp() {
        magicLoopAction();
        someOtherMagicStuff();
    }
    function magicLoopAction() {
        for (var i = 0; i < 42; i++) { 
            // whoopwhoop
        }
    }
    function someOtherMagicStuff() {
        for (var i = 0; i < 69; i++) { 
            // lint is happy and proud on you
        }
    }
    

提交回复
热议问题