Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable scope inside for loop

Tags:

javascript

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 helpful. Thank you!

var el, 
    len = statesPolyStrings.length;

for (var i = 0; i < len; i++) {
    el = document.getElementById(statesPolyStrings[i]);

    google.maps.event.addDomListener(el, 'mouseover', function() {
        $("#"+statesPolyStrings[i]).addClass("highlight");
        statesPolyObjects[i].setOptions({ strokeWeight: '2' });
    });
}
like image 537
chris_mac Avatar asked Jun 08 '12 18:06

chris_mac


1 Answers

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);
}
like image 111
SLaks Avatar answered Sep 16 '22 12:09

SLaks