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

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

本文关键字:循环 for 迭代器 回调 Javascript-      更新时间:2023-09-26

我正在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
    });             
}

它调用。。。

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本身,而不是当前值。尝试:

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

这将为每个循环迭代创建新的CCD_ 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. 它被调用的数组

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


如果a是一个没有forEachNodeList,只需执行:

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