I am trying in the for loop to access the value of the i with which the callback function uses.
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 calls...
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.")
}
});
}
Probably the most elegant way to do it is just using
Array.forEach
:The callback function gets passed:
Leaving out arguments just means you can’t access them in the callback. (Often you leave out the index and just use the current element).
If
a
is aNodeList
, which doesn’t haveforEach
, just do:It's because the closure captures the variable
i
itself, not the current value. Try:which will create a new
i
variable for each loop iteration.