如何在jQuery中将项目添加到数组中? [英] How do I add items to an array in jQuery?

查看:164
本文介绍了如何在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中将项目添加到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆