最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - how to work with the iterator in a for loop with callbacks - Stack Overflow

programmeradmin0浏览0评论

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.")
        }       
    }); 
}

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.")
        }       
    }); 
}
Share Improve this question asked Feb 21, 2012 at 12:54 Valentin DespaValentin Despa 42.6k18 gold badges83 silver badges108 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

It's because the closure captures the variable i itself, not 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 i variable for each loop iteration.

Probably the most elegant way to do it is just using 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 gets passed:

  1. the current element
  2. the current index
  3. the array it was called upon

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 a NodeList, which doesn’t have forEach, just do:

Array.forEach.call(a, function(someA, i) { ... }
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));
}
发布评论

评论列表(0)

  1. 暂无评论