0

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>
3

2 Answers 2

3

Change it to:

$.getJSON('list.json', function(data) {
  $.each(data['pranks'], function(key, val) {
    pranks.push(val);
  });
  alert(pranks.length); /* pranks has data now */
});
Sign up to request clarification or add additional context in comments.

Comments

1

Taking your code:

<script type="text/javascript">
(function() { 
    function getAllPranks( callback ) {
        $.getJSON('list.json', function(data) {
            $.each(data['pranks'], function(key, val) {
                pranks.push(val);
            });
            callback( pranks );
        });
    }

    $(document).ready(function(){
        getAllPranks( function( pranks ) {
            alert(pranks.length);
        } );
    });
}());
</script>

$.getJSON is asynchronous. This means the callback function (function(data)) is executed once the result comes back. When you execute alert(pranks.length), the function has not executed because the response hasn't come back at this moment.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.