0
var locations = [];
$.getJSON("locations.json", function(json) {
  console.log(json);
  json.forEach(function(locItem){
    locations.push(locItem);
  });
});

console.log(locations);

The line 3 log did print my json list but the line 9 log only gives []. I tried using window.locations, global.locations or define something like

var self = this;

in global scope and then use self.locations inside the funciont. None of them works.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Siyu
  • 37
  • 1
  • 8

2 Answers2

1

This happens because the order of execution is as follows:

// create empty array
var locations = [];

// attempt to get json file (locations is unchanged)
$.getJSON("locations.json", callback); 

// print out empty locations variable
console.log(locations);

// json is finally retrieved, and the callback function is processed
function callback(json) {
    console.log(json);
    json.forEach(function(locItem){
        locations.push(locItem);
    });
});

The callback function is not called until the json has been retrieved. It does not wait for that to happen.

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
Matt Way
  • 32,319
  • 10
  • 79
  • 85
0

Try:

   var locations = [];
    $.getJSON("locations.json", function(json) {
      console.log(json);
      json.forEach(function(locItem){
        locations.push(locItem);
      });
    }).then(function() {
          console.log(locations);
   });
Patricia
  • 2,885
  • 2
  • 26
  • 32