I have next code which load an file json, and make an array called questions.
if i do an console.log(JSON.stringify(questions)) inside getArray function it works ok, but if I do the same outsite the function it doesn't work, I tried with
alert(JSON.stringify(questions)) and alert(questions.length) it return [] and 0, where's my mistake??
var questions = [];
function getArray(){
$.getJSON('questions.json', function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
questions.push({
Category: item.Category
});
}
}
//console.log(JSON.stringify(questions)); //it works
return questions;
});
}
$(document).ready(function(){
getArray();
});
alert(JSON.stringify(questions)) //return []
alert(questions.length) //return 0
alert()s are synchronous and execute before anything else because the rest is asynchronous and event-driven. Just because code is written in a particular order doesn't guarantee it executes in that same order, especially when working with events.