In JavaScript, when looping through a FOR loop, how do I pass the value of the item in an array to an anonymous function?

Bassmanjase

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.

MrCode

You can use a closure around the addListener part:

(function(text){
    google.maps.event.addListener(marker, 'click', function () { ShowMarkerContentPopUp(this, text); });
})(text);

This creates a new scope and takes the text variable as an argument. It means the text inside the closure is protected from being changed outside of the closure.

The same can be done to solve your first example:

for (var i = 0; i < aStrings.length - 1; i++) {
    (function(i){
        aFunctions[i] = function () { alert(aStrings[i]); };
    })(i);
}

More info on closures:

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to pass looping through multidimentional array into function

In Javascript, when looping through an array of objects, how do I send each element's name to the console?

JavaScript Filter Loop Not Looping Through All Item In Array

How do I loop through each array item and divide by two?

How do I pass a value to a function in JavaScript?

How do I pass an anonymous function to map()?

Scheme - How do I loop an anonymous function?

When looping through values of a JS array, and I remove value, do I need to use while instead of for?

How do I loop through array and call function for each?

How do I loop through an array for a particular value in CoffeeScript

How do I loop through a javascript array of audio files?

When looping through an array of objects I get a null value error

When creating buttons for each item in an array in React, how do I pass in unique onClick parameters based on the array value?

Why do I get weird integers when looping through an array

How do I remove something from an array list when looping through it in java?

How to pass array into anonymous function?

How do i loop through and array of an array

How to Pass An Array Through a Function Parameter - javascript

How can I loop through an array in React using the while loop and pass the index value?

For in loop looping through array but not JS function

How to loop through array and assign every item a value without loop?

how do I create multiple CRON function by looping through a list

How do I pass a text value that contains an apostrophe to a javascript function

How do I pass an empty array as a default function parameter in Javascript?

Value changing when I pass array into function

How do I loop through a JSON array?

How Do I loop through this POST array?

How do i loop through an array backwards?

How do I loop through a JavaScript object?

TOP Ranking

HotTag

Archive