如何在 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,它的格式良好,一切看起来都很好。我似乎无法将项目添加到数组中,我缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于
$.getJSON
是异步的,我认为您的console.log(list.length);
代码是在填充数组之前触发的。要纠正此问题,请将console.log
语句放入回调中:Since
$.getJSON
is async, I think yourconsole.log(list.length);
code is firing before your array has been populated. To correct this put yourconsole.log
statement inside your callback:希望这会帮助你..
Hope this will help you..
您正在发出异步 ajax 请求,因此列表长度的控制台日志会在 ajax 请求完成之前发生。
实现您想要的唯一方法是将 ajax 调用更改为同步。您可以通过使用 .ajax 并传入 asynch : false 来做到这一点,但是不建议这样做,因为它会锁定 UI,直到调用返回,如果返回失败,用户必须从浏览器中崩溃。
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.