本文介绍了如何在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始终返回0.我在firebug中浏览了JSON,它的格式正确,一切都很好.我只是似乎无法将一个项目添加到数组中,所以我缺少了什么?
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?
推荐答案由于$.getJSON是异步的,我认为您的console.log(list.length);代码在填充数组之前就已触发.要更正此问题,请将您的console.log语句放入回调中:
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); });更多推荐
如何在jQuery中将项目添加到数组中?
发布评论