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

javascript can not iterate array after reading JSON file

本文关键字:迭代 数组 文件 读取 JSON javascript      更新时间:2023-09-26

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

在这里,我试图在读取JSON文件后迭代tempList数组。但是console.log没有显示任何内容。但如果我尝试console.log(tempList),它会起作用。tempList是一个全局变量。我正在从另一个函数调用readJson函数。JSON文件保存在此处JSON文件

由于$.getJSON是异步的,在实际获取任何数据之前,您似乎正在运行for循环。因此,请尝试将迭代器循环移动到$.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函数。这意味着当您已经开始console.log tempList的内容时,它正在从url(在另一个线程中)加载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函数:

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