Javascript - how to work with an iterator in a for loop with callbacks

I'm trying in a for loop to access the i value that the callback function works with.

How can i do this?

for (var i = 0; i < a.length; i++) { calcRoute(fixedLocation, my_cities[i].address, function(response) { // i want here to have the current "i" here }); } 

which causes ...

 function calcRoute(x, y, callback) { var start = x; var end = y; var request = { origin:start, destination:end, travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, optimizeWaypoints: true }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { callback(response); } else { alert("City unknown.") } }); } 
+7
source share
3 answers

This is because the closure captures the variable i rather than the current value. Try:

 for (var i = 0; i < a.length; i++) (function(i) { calcRoute(fixedLocation, my_cities[i].address, function(response) { // i want here to have the current "i" here }); }) (i); 

which will create a new variable i for each iteration of the loop.

+12
source

Probably the most elegant way to do this is to simply use Array.forEach :

 a.forEach(function(someA, i) { calcRoute(fixedLocation, my_cities[i].address, function(response) { // i want here to have the current "i" here }); }); 

The callback function is passed:

  • current item
  • current index
  • the array to which it was called

Leaving the arguments simply means that you cannot access them in the callback. (Often you do not specify an index and just use the current element).


If a is a NodeList that does not have forEach , simply do:

 Array.forEach.call(a, function(someA, i) { ... } 
+2
source
 for (var i = 0; i < a.length; i++) { function createCallback(i) { return function(response) { // i want here to have the current "i" here } } calcRoute(fixedLocation, my_cities[i].address, createCallback(i)); } 
+1
source

All Articles