I’m trying to add a set of objects that have been retrieved from a JSON file into an array. I’ve tried using push but the result is the same. The length value of the array remains 0. What am I doing wrong? The JSON parses fine as I can get the values during the loop.
<script type="text/javascript">
//my array
var myArray = new Array();
function performSearch(){
var url = "http://myjsonurl...";
var counter = 0;
$.getJSON(url, function(response){
$.each(response.data.people, function() {
//p is the the object to add to the array
var p = new person(this.name, this.age);
//tried using myArray.push instead of having a counter, but
//I get the same length of 0.
myArray[counter] = p;
counter++;
});
});
//always returns 0
alert(myArray.length);
}
...
</script>
getJSON()is an asynchronous function. It only starts to fetch the data when you call it, and it calls the given function only after it has loaded it. So you call the alert before anything is fetched. You should have the alert right after the .each() function.