How do I add items to an array in jQuery? How do I add items to an array in jQuery? json json

How do I add items to an array in jQuery?


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


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.


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