Dealing with duplicate declaration warning for loop variables

前端 未结 5 1919
傲寒
傲寒 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:37

    I recommend enclosing your loops within self-executing functions whose names tell you what the loop is doing. This effectively gives block scope to the loop. For example:

    var users = response['users']
    ;(function appendUsers(){
        for (var i = 0; i < users.length; i++) {
            var user      = users[i]
            var userEmail = user['email']
            var userId    = user['id']
            /* etc */ 
        }
    })() // appendUsers
    

    If you do this:

    var i
    for (i = 0; i < someVar.length; i++) {
        for (i = 0; i < someOtherVar.length; i++) {
            // This is a bug that a validator will not notice.
        }
    }
    

    On the other hand:

    for (var i = 0; i < someVar.length; i++) {
        for (var i = 0; i < someOtherVar.length; i++) {
            // This is a bug that a validator will warn you about.
        }
    }
    for (var i = 0; i < yetAnotherVar.length; i++) {
        // It will also warn you about this, but so what?
    }
    

    You can stop using i as an iterator:

    for (var companyIndex = 0; companyIndex < companies.length; companyIndex++) {
        var company = companies[companyIndex]
    }
    

    If you're using jQuery anyway, you can use its jQuery.each() method:

    $.each(someVar, function(i, value){
        // etc
    })
    

    You can't use Array.prototype.forEach() if you want IE8 and earlier to work, unless you add the Polyfill code or similar.

提交回复
热议问题