Javascript - 如何在带有回调的for循环中使用迭代器

Val*_*spa 8 javascript callback

我正在尝试在for循环中访问回调函数使用的i的值.

我怎样才能做到这一点?

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

    });             
}
Run Code Online (Sandbox Code Playgroud)

哪个叫......

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.")
        }       
    }); 
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lin 14

这是因为闭包捕获变量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);
Run Code Online (Sandbox Code Playgroud)

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