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

后端 未结 3 1199
无人共我
无人共我 2020-12-31 14:24

I am trying in the for loop to access the value of the i with which the callback function uses.

How can I do this?

for (var i = 0; i < a.length; i         


        
相关标签:
3条回答
  • 2020-12-31 14:56

    It's because the closure captures the variable i itself, not the current value. Try:

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

    which will create a new i variable for each loop iteration.

    0 讨论(0)
  • 2020-12-31 15:01
    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));
    }
    
    0 讨论(0)
  • 2020-12-31 15:11

    Probably the most elegant way to do it is just using Array.forEach:

    a.forEach(function(someA, i) {
        calcRoute(fixedLocation, my_cities[i].address, function(response) {
    
            // i want here to have the current "i" here
    
        });
    });
    

    The callback function gets passed:

    1. the current element
    2. the current index
    3. the array it was called upon

    Leaving out arguments just means you can’t access them in the callback. (Often you leave out the index and just use the current element).


    If a is a NodeList, which doesn’t have forEach, just do:

    Array.forEach.call(a, function(someA, i) { ... }
    
    0 讨论(0)
提交回复
热议问题