0

我正在使用 Papa Parse 解析 csv 文件。在“完成”中,我尝试将结果(对象数组)分配给我在调用 Papa Parse 的 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??
    }
}

4

1 回答 1

0

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

于 2014-12-01T13:55:13.920 回答