2012-02-21 13 views
7

Estoy intentando en el ciclo for acceder al valor de la i con la que utiliza la función de devolución de llamada.Javascript - cómo trabajar con el iterador en un bucle for con devoluciones de llamada

¿Cómo puedo hacer esto?

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 

    });    
} 

que se pide ...

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

Respuesta

12

Es porque el cierre capta la variable i en sí, no el valor actual. Proveedores:

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

que creará una nueva variable i para cada iteración del bucle.

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

Probablemente la forma más elegante de hacerlo es sólo con Array.forEach:

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

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

    }); 
}); 

La función de devolución de llamada se pasa:

  1. el elemento actual
  2. el índice actual
  3. la matriz a la que se llamó

Dejar argumentos solo significa que no puede acceder a ellos en la devolución de llamada. (A menudo omite el índice y simplemente usa el elemento actual).


Si a es una NodeList, que no tiene forEach, acaba de hacer:

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