2016-10-26 42 views
0
var locations = []; 
$.getJSON("locations.json", function(json) { 
    console.log(json); 
    json.forEach(function(locItem){ 
    locations.push(locItem); 
    }); 
}); 

console.log(locations); 

第3行日誌確實打印了我的json列表,但第9行僅記錄了[]。我試圖在全球範圍內使用window.locations,global.locations或定義類似將json數據加載到javascript全局變量

var self = this; 

,然後使用funciont內self.locations。它們都不起作用。

回答

0

這是因爲執行的順序如下:

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

回調函數不叫,直到JSON已經被檢索。它不會等待發生。

0

嘗試:

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