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

时间:2014-11-30 01:36:13

标签: javascript parsing papaparse

我正在使用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??
    }
}

1 个答案:

答案 0 :(得分:0)

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