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?
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With