1

I am trying to store the results from a json callback function in an array. Basically what i have now is an array of gps coordinates stored that i am iterating through and for each pair of coordinates i am creating a script that sends requests to a third party.

int j = 0;
while(j < points.length-3)
{
   window['streetNames'+j] = function(json){
                             console.log("YO",j);
                             streetNames(json, j);
                             }; 

   var reverse = document.createElement('script'); 
   reverse.src = 'http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&json_callback=streetNames'+j+'&lat='+points[j]+'&lon='+points[j+1];
   document.getElementsByTagName('head')[0].appendChild(reverse);
   j = j + 2;
}

In order to be able to store the results in the proper order i have to pass an index to the callback function and the only way i found possible by sticking the j index to the name of the function.

var streets = [];
function streetNames(json, t)
{
    console.log("in streetNames", t);
    streets[t] = json.address.road;
}

However, after running the script the only instance that gets added to the streets array is the last one of the points array, the one of the last index. My question is, shouldn't all the gps coordinates run the window['streetNames'+j] = function(json) function? What am i doing wrong?

user3253067
  • 113
  • 2
  • 11

1 Answers1

3

As noted in the answers on the duplicate question, Javascript has only function scope and closures take variables by reference. This means that all your closures see the same j, which eventually is updated to the last value the loop sets. You should use bind. Please note that I have also replaced int with var and have changed the order of arguments for streetNames.

var j = 0;
while(j < points.length-3)
{
   window['streetNames'+j] = streetNames.bind(this, j);
   // ...
}

var streets = [];
function streetNames(t, json)
{
    console.log("in streetNames", t);
    streets[t] = json.address.road;
}
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98