Search code examples
jqueryjsonfirebuggetjson

How do I add items to an array in jQuery?


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?


Solution

  • 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);
    });