I am trying to create an array in my JavaScript object that contains objects pulled in from a JSON file using the $.getJSON() function in jQuery. I am running into scope issues where it seems like the array elements are getting set inside the $.getJSON() function, but outside of it the array is empty. Here is the code:
function player(playlist){
...
var tracks = [];
this.start = function() {
...
$.getJSON(playlist, function(data){
$.each(data.tracks, function(key,value){
var track_info = function(info){return info}(value);
tracks.push(track_info);
});
console.log("from .getJSON function");
console.log(tracks);
});
console.log("outside .getJSON function");
console.log(tracks);
...
};
...
$(document).ready(function(){
var the_player = new player(playlist);
the_player.start();
)};
The output is:
outside .getJSON function
[]
from .getJSON function
[Object, Object, Object]
And all the objects contain the correct data from the JSON file.
I'm perplexed about this issue, can someone help me understand it?