2012-02-21 38 views
7

我想在for循环中访问回调函数使用的i的值。Javascript - 如何使用迭代器在for循环中使用回调

我该怎么做?

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 

    });    
} 

这就要求...

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

回答

12

这是因为封闭拍摄变量i本身,而不是当前值。尝试:

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); 

这将为每个循环迭代创建一个新的i变量。

1
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)); 
} 
2

可能是最优雅的方式来做到这一点是在运用Array.forEach

a.forEach(function(someA, i) { 
    calcRoute(fixedLocation, my_cities[i].address, function(response) { 

     // i want here to have the current "i" here 

    }); 
}); 

回调函数会得到:

  1. 当前元素
  2. 目前指数
  3. 它被呼叫的阵列

抛出参数意味着你不能在回调中访问它们。 (通常你忽略索引,只使用当前元素)。


如果aNodeList,不具有forEach,只是做:

Array.forEach.call(a, function(someA, i) { ... }