What is a good way to declare a new, unique variable in each iteration of a for-loop in javascript?

<>

This question already has an answer here:

Answers


As sayed above, you need closure:

for (loc in locations){
  (function(loc){  
    var newLoc = locations[loc].split(", ")
    var uniquevar = new google.maps.Marker({
      position: new google.maps.LatLng(newLoc[0], newLoc[1]),
      map: map,
     title: loc
    });

    google.maps.event.addListener(loc, 'click', function() {
      console.log(loc);
    });
  })(loc);
};

You need to create a closure. By creating a closure, you effectively 'bake' the state of the internal function at the time of execution, which is NOT the same time as the 'click' handler is fired.

EDIT: Removed terrible code - use Nayjest's much cleaner solution above!


Need Your Help

Update a specific R package and its dependencies

r cran

I have around 4000 R packages installed in my system (a server) and most of them are outdated because they were built before R-3.0.0. Now I know

How to make matplotlib Density Map

matplotlib

Let's say I have two lists, x and y of same length. This length is not fixed, but always nonzero. They are x and y values of non-negative points.