加载json数据到javascript全局变量

load json data to javascript global variable

本文关键字:javascript 全局变量 数据 json 加载      更新时间:2023-09-26
var locations = [];
$.getJSON("locations.json", function(json) {
  console.log(json);
  json.forEach(function(locItem){
    locations.push(locItem);
  });
});
console.log(locations);

第3行日志确实打印了我的json列表,但第9行日志只给出[]。我尝试使用窗口。位置,全球。或者定义像

这样的东西
var self = this;

在全局作用域中,然后使用self。函数内部的位置。

这是因为执行顺序如下:

// 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被检索到。它不会等待发生

尝试:

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