从csv中读取后删除脚本数组

时间:2019-04-26 18:42:01

标签: javascript

尝试使用Javascript中的文件读取器读取CSV文件,我更新了脚本声明的数组。但是读取完成后,将删除数组中的所有数据。我不确定为什么会这样,这对js来说还很新。我认为这是由于数组的范围所致,但我将它们声明为全局数组,但仍然无法正常工作。

var paper = [];
var recyclables = [];
var compost = [];
var landfill = [];

function readCsvFileData(type, index) {
    readCsv();
    if(type == "paper"){
        console.log("requested type - " + paper.length);
        console.log("wrong answer here -- 0 ");
        return paper[index];
    }
}


function readCsv() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200){
            console.log(this.responseText);
            var line = this.responseText.split("\n");
            for(let row = 1; row < line.length; row++){
                let rowData = line[row].split(',');
                for(let col = 1; col < rowData.length; col++){
                    if(col == 1 && paper.length<12){
                        paper.push(rowData[col]);
                    }
                    if(col == 2 && recyclables.length<12){
                        recyclables.push(rowData[col]);
                    }
                    if(col == 3 && compost.length<12){
                        compost.push(rowData[col]);
                    }
                    if(col == 4 && landfill.length<12){
                        landfill.push(rowData[col]);
                    }
                    if(paper.length==12 && recyclables.length==12 && compost.length==12 && landfill.length==12){
                        console.log("retruning "+landfill.length);
                        console.log("correct answer here -- 12");
                        return true;
                    }
                }
            }
        }
    }
    xhttp.open('GET', "Data.csv", true);
    xhttp.send();
}

1 个答案:

答案 0 :(得分:1)

正如Jay Buckman在评论中提到的那样,您正在异步执行此操作,这意味着函数readCsv立即返回,而不是等待send()方法完成。届时,您的readCsvFileData函数将继续存在的if条件,该条件正在处理尚未填充的数组。您需要添加事件侦听器/回调方法。试一试:

var paper = [];
var recyclables = [];
var compost = [];
var landfill = [];

function readCsvFileData(type, index) {
    readCsv(function() {
        if(type == "paper"){
            console.log("requested type - " + paper.length);
            console.log("wrong answer here -- 0 ");
            return paper[index];
        }
    });
}


function readCsv(onCompleteCallback) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200){
            // ... your normal implementation

            // invoke your complete callback, which will run the function
            // you passed through to this function
            onCompleteCallback();
        }
    }

    xhttp.open('GET', "Data.csv", true);
    xhttp.send();
}

Here's some further reading on the topic。通常,首选设置async参数。没有它,您的调用将同步发生,这可能会锁定主线程(即用户浏览器)直到完成,这是不理想的。