Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 405
NATO24 Avatar asked Aug 30 '09 06:08

NATO24


People also ask

Can you append to an array in JavaScript?

Sometimes you need to append one or more new values at the end of an array. In this situation the push() method is what you need. This method accepts an unlimited number of arguments, and you can add as many elements as you want at the end of the array.


1 Answers

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); }); 
like image 187
Derek Swingley Avatar answered Sep 20 '22 05:09

Derek Swingley