Here’s my code. If i check “pranks” variable by “google inspector” all works fine.
But the “alert” on the last line show a 0-size array!
I mucking with local/global variables?
<script type="text/javascript">
(function() {
pranks = [];
function getAllPranks(){
$.getJSON('list.json', function(data) {
$.each(data['pranks'], function(key, val) {
pranks.push(val);
});
});
}
$(document).ready(function(){
getAllPranks();
alert(pranks.length);
});
}());
</script>
Taking your code:
$.getJSONis asynchronous. This means the callback function (function(data)) is executed once the result comes back. When you executealert(pranks.length), the function has not executed because the response hasn’t come back at this moment.