Array of objects not able to be referenced outside of function

时间:2018-03-25 18:54:43

标签: javascript html

Loading in data from a json file and trying to use it outside of this function

function loadJSON() {
    //load location info into array to be used by positions/colors/size loop
    $.getJSON('lib/js/data/brand.json', function(data) {
       
        for ( var j = 0; j < data[0].locations.length; j++ ) {
            var point = {};         // New point object 
            point.id = (data[0].locations[j].brand) + j; // Brand name + id 
            point.lat = (data[0].locations[j].lat);          // lat property
            point.long = (data[0].locations[j].long);         // long property
            points.push(point); 
        }

        
    });
}

when I call the functioin and try to reference a point, it's undefined

    loadJSON();
    console.log(points[0]);

if I just console.log(points), I get something like this 

[]
0
:
{id: "arbys0", lat: "39.1031", long: "-84.512"}
1
:
{id: "arbys1", lat: "39.1031", long: "-84.512"}

1 个答案:

答案 0 :(得分:0)

Javascript has function scoping (with var) and block scoping (with const and let). Variables defined inside blocks/functions can't be accessed outside of those blocks/functions.

Either declare points in the upper scope (and make sure you wait long enough for the request to come back, since Javascript doesn't block), or - a better option - make a Promise that resolves with the created points.

Eg, you might want something like:

function loadJSON() {
  //load location info into array to be used by positions/colors/size loop
  fetch('lib/js/data/brand.json')
  .then(res => res.json())
  .then(data => {
    var points = [];
    for ( var j = 0; j < data[0].locations.length; j++ ) {
      var point = {};         // New point object 
      point.id = (data[0].locations[j].brand) + j; // Brand name + id 
      point.lat = (data[0].locations[j].lat);          // lat property
      point.long = (data[0].locations[j].long);         // long property
      points.push(point); 
    }
    return points;
  })
  .then(functionThatDoesSomethingWithPoints)
}

function functionThatDoesSomethingWithPoints(points) {
  // code here
}