Javascript variable scope inside for loop

前端 未结 3 1881
感动是毒
感动是毒 2020-12-03 08:45

How do I maintain access to the i variable inside my for loop below? I\'m trying to learn, not just get the answer, so a bit of explanation would be very helpfu

3条回答
  •  無奈伤痛
    2020-12-03 08:59

    All of your callbacks share the same i variable.
    When the event handler actually runs, i is after the end of the array.

    You need to wrap the loop body in a self-invoking function that takes i as a parameter.
    This way, each iteration will get its own, unchanging, i variable.

    For example:

    for (var i = 0; i < statesPolyStrings.length; i++) {
        (function(i) {
            ...
        })(i);
    }
    

提交回复
热议问题