How do I add items to an array in jQuery?

前端 未结 3 1017
慢半拍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 07:39

    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.

提交回复
热议问题