59
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?

DᴀʀᴛʜVᴀᴅᴇʀ
  • 4,253
  • 12
  • 46
  • 84
NATO24
  • 898
  • 1
  • 7
  • 14
  • This seems right. Does the `$.each` loop print items to the log, but doesn't add them to `list`? – Kobi Aug 30 '09 at 06:42

3 Answers3

123

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);
});
DᴀʀᴛʜVᴀᴅᴇʀ
  • 4,253
  • 12
  • 46
  • 84
Derek Swingley
  • 8,574
  • 5
  • 28
  • 31
3

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });
aji
  • 31
  • 1
3

You are making an ajax request which is asynchronous therefore your console log of the list length occurs before the ajax request has completed.

The only way of achieving what you want is changing the ajax call to be synchronous. You can do this by using the .ajax and passing in asynch : false however this is not recommended as it locks the UI up until the call has returned, if it fails to return the user has to crash out of the browser.

redsquare
  • 75,782
  • 18
  • 147
  • 156