使用Papa Parse为什么我不能引用已经解析的数据

Using Papa Parse why can I not reference the data that has been parsed?

本文关键字:数据 引用 Parse Papa 为什么 不能 使用      更新时间:2023-09-26

我正在使用Papa Parse来解析csv文件。在"完整"中,我尝试将结果(对象数组)分配给我在调用 Papa Parse 的解析函数之外声明的变量。变量在函数内部很好,但在函数外部未定义。 我也尝试了使用字符串和整数,但变量在函数外部仍未定义。

var data;
for (var i = 0, f; f = files[i]; i++) {
    if (f.type == 'application/csv' || f.type == 'application/vnd.ms-excel' || f.type == 'text/csv') {
        Papa.parse(f, {
            header: true,
            dynamicTyping: false,
            complete: function(results) {
                console.log("Completed parsing results", results);
                data = results.data.slice(0); //I tried other simple values here, such as "test"
                console.log("Data after assigned value.", data); //Here the data is correctly assigned to the variable
            }
        });
        console.log("Value of data outside function.", data); //Undefined??
    }
}

解析

文件是异步的,这就是为什么你的最后一个控制台.log行没有任何结果:它在解析完成之前执行。对结果的处理必须在complete回调内部或之后进行。