簡體   English   中英

Javascript - 如何在帶有回調的for循環中使用迭代器

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

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

這將為每個循環迭代創建一個新的i變量。

可能最優雅的方法就是使用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) { ... }
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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM