In JavaScript, I need to loop through a for
loop to get the value of an item in an array, and pass this to an anonymous function. A simplified example of this is below:
var aFunctions = [];
var aStrings = ["a","b","c"];
for (var i = 0; i < aStrings.length - 1; i++) {
aFunctions[i] = function () { alert(aStrings[i]); };
}
aFunctions[0](); //alerts "c" instead of "a"
I can see why this is happening - the variable i
is being set to 2
when the loop exits, and then when I call aFunctions[0]()
, the function fires off and evaluates aStrings[i]
rather than aStrings[0]
.
What I want to know is how to get the value of aStrings[i]
returned within my for
loop, and not when it's executed.
To give more specific detail, I'm working on a Google Maps page, and the markers are stored in a JavaScript array client-side, and in a DB server-side. I write the array at page-load and after that's complete I want to generate the markers, and give them each a custom InfoWindow with the text set to an HTML string. This is the specific code I use:
for (var i = 0; i < tGoogleMarker.length - 1; i++) {
var text = tGoogleMarker[i][4];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(tGoogleMarker[i][0], tGoogleMarker[i][1]),
map: map,
flat: false,
icon: tGoogleMarker[i][2],
shadow: tGoogleMarker[i][3]
});
google.maps.event.addListener(marker, 'click', function () { ShowMarkerContentPopUp(this, text); });
}
Instead of getting the HTML string of the specific marker, I get the text of the last item in the array used for all markers.