使用 json 数据填充现有数组

Populate existing array with json data

本文关键字:数组 填充 json 数据 使用      更新时间:2023-09-26

我用 JSON 返回的数据填充现有数组几乎没有什么麻烦。这是我所拥有的

myarr=[];
function fillarr()
    {
    $.getJSON("test.php?c=10",function(data)
            {
            $.each(data, function(key, val)
                    {
                    myarr.push(data[val]);
                    }
                    });
            });
    }

我的问题是,数组在函数之外是emty。请帮忙。

myarr=[];
function fillarr()
    {
    $.getJSON("test.php?c=10",function(data)
            {
            $.each(data, function(key, val)
                    {
                        myarr.push(val);
                        console.log(myarr); // you will myarr here, not out side
                    }
                    });
            });
      console.log(myarr); // wont get
    }

myarr ajax 请求完成后获取其内容并花费时间。 所以console在请求完成之前执行 $.getJSON 之外。

myarr=[];
function fillarr()
{
    $.getJSON("test.php?c=10", function(data) {
        $.each(data, function(key, val) {
            myarr.push(val);
        });
        doSomethingNowThatTheArrayIsActuallyPopulated();
    });
}
fillarr();
console.log(myarr); // This will print an empty array, it hasn't been populated yet.
function doSomethingNowThatTheArrayIsActuallyPopulated() {
    console.log(myarr); // This will print the array which now contains the json values
}

如果返回数据是一个对象,则更容易执行jQuery.each将每个值推送到数组。

function fillarr(){
    $.getJSON("test.php?c=10",function(data){
        $.each(data, function(key, val){
            myarr.push(val);
        });
    });
}

如果返回数据是数组,则数组连接会更快

function fillarr(){
    $.getJSON("test.php?c=10",function(data){
        myarr = myarr.concat(data);
    });
}