如何将项目添加到 jQuery 中的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1353245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:16:49  来源:igfitidea点击:

How do I add items to an array in jQuery?

jqueryjsonfirebuggetjson

提问by NATO24

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.lengthalways 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?

list.length总是返回 0。我在 firebug 中浏览了 JSON,它的格式很好,一切看起来都很好。我似乎无法向数组中添加一个项目,我缺少什么?

回答by Derek Swingley

Since $.getJSONis async, I think your console.log(list.length);code is firing before your array has been populated. To correct this put your console.logstatement inside your callback:

由于$.getJSON是异步的,我认为你的console.log(list.length);代码在你的数组被填充之前就被触发了。要更正此问题,请将您的console.log语句放入回调中:

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

回答by redsquare

You are making an ajax request which is asynchronous therefore your console log of the list length occurs before the ajax request has completed.

您正在发出一个异步的 ajax 请求,因此列表长度的控制台日志发生在 ajax 请求完成之前。

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.

实现您想要的唯一方法是将 ajax 调用更改为同步。您可以通过使用 .ajax 并传入 asynch : false 来完成此操作,但不建议这样做,因为它会在调用返回之前锁定 UI,如果返回失败,则用户必须从浏览器中崩溃。

回答by aji

Hope this will help you..

希望能帮到你..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });