How do I add items to an array in jQuery?

NATO24 picture NATO24 · Aug 30, 2009 · Viewed 306.7k times · Source
var list = [];
$.getJSON("json.js", function(data) {
    $.each(data, function(i, item) {
        console.log(item.text);
        list.push(item.text);
    });
});
console.log(list.length);

list.length always returns 0. I've browsed the JSON in firebug and it's well formed and everything looks fine. I just can't seem to add an item to the array what am I missing?

Answer

Derek Swingley picture Derek Swingley · Aug 30, 2009

Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

var list = new Array();
$.getJSON("json.js", function(data) {
    $.each(data, function(i, item) {
        console.log(item.text);
        list.push(item.text);
    });
    console.log(list.length);
});