How do I add items to an array in jQuery?

前端 未结 3 1014
慢半拍i
慢半拍i 2021-01-31 07:25
var list = [];
$.getJSON(\"json.js\", function(data) {
    $.each(data, function(i, item) {
        console.log(item.text);
        list.push(item.text);
    });
});
con         


        
3条回答
  •  长情又很酷
    2021-01-31 08:03

    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);
    });
    

提交回复
热议问题