javascript在读取JSON文件后无法迭代数组

javascript在读取JSON文件后无法迭代数组,javascript,jquery,arrays,json,Javascript,Jquery,Arrays,Json,我是javascript新手。我对简单的json文件读取有问题。下面是示例代码 function readJson() { $.getJSON('./resources/json/comments_type.json', function(data) { $.each(data, function(index, comment) { tempList.push(comment); });

我是javascript新手。我对简单的json文件读取有问题。下面是示例代码

   function readJson() {
        $.getJSON('./resources/json/comments_type.json', function(data) {
            $.each(data, function(index, comment) {
                tempList.push(comment);
            });
        });



        for(var i = 0 ; i<tempList.length;i++)
        {
            console.log(tempList[i].text);
        }

    }
函数readJson(){ $.getJSON('./resources/json/comments_type.json',函数(数据){ $。每个(数据、函数(索引、注释){ 圣殿骑士推(评论); }); });
for(var i=0;i在实际获取任何数据之前,您似乎正在运行for循环,因为$.getJSON是异步的。因此,请尝试将迭代器循环移动到$.getJSON回调

function readJson() {
    $.getJSON('./resources/json/comments_type.json', function(data) {
        $.each(data, function(index, comment) {
            tempList.push(comment);
        });

        //Here you should have the list
        for(var i = 0 ; i<tempList.length;i++)
        {
            console.log(tempList[i].text);
        }
    });
}
函数readJson(){ $.getJSON('./resources/json/comments_type.json',函数(数据){ $。每个(数据、函数(索引、注释){ 圣殿骑士推(评论); }); //这是你的名单
for(var i=0;ireadJSON函数是异步调用的。这意味着,当您已经开始console.log tempList的内容时,它正在从url(在另一个线程中)加载JSON。请确保在下载临时列表后读取它。这通常是通过回调完成的。或者您可以使此请求同步(但这是错误的方法)

然后在代码中的其他地方:

readJson(function(){
    for(var i = 0 ; i<tempList.length;i++)
       {
          console.log(tempList[i].text);
       }
});
readJson(函数(){

对于(var i=0;我可以发布您是如何创建tempList的吗?您(错误地)使用了{}而不是[]吗?谢谢。我已经检查过了。我使用了tempList=[]你能在哪里编辑这段代码吗?似乎有一些与scopeedited有关的东西。谢谢你的回复。的可能副本工作得很好!非常感谢!我忘记了js中的异步调用。
    function readJson(callback) {
    $.getJSON('./resources/json/comments_type.json', function(data) {
        $.each(data, function(index, comment) {
            tempList.push(comment);
        });
       callback();
    });     
 }
readJson(function(){
    for(var i = 0 ; i<tempList.length;i++)
       {
          console.log(tempList[i].text);
       }
});