0
var items = [];
$(document).ready(function() {
    $.getJSON("locations.json", function(data) {

        $.each(data, function(key, val) {
            items.push(val);
            console.log(items[1]);

        });
    });
});
console.log(items[1]);

I am trying to learn how to use JSON to dyamically update pages in a Jquery Mobile Project. At the moment I am just experimenting to try and learn how to access my data so the code above is not doing anything practicle but have discovered a problem below which I do not understand.

The last line of code outputs "undefined" to the console where the same code output the data inside the loop.

Why are items pushed to the array not accessible outside of the loop?

Pointy
  • 405,095
  • 59
  • 585
  • 614

1 Answers1

2

That last console.log() is not only outside of the iteration, it's also outside of your "ready" handler. It'll run before the code in the handler runs.

If it were inside the "ready" handler, then you'd face a similar problem: $.getJSON() is asynchronous, so the callback you pass in to that function will also run after your console.log(). The only reliable way to get to the list of items is inside that inner callback function.

Pointy
  • 405,095
  • 59
  • 585
  • 614