gpt4 book ai didi

javascript读取csv文件返回空数组

转载 作者:行者123 更新时间:2023-11-28 03:57:09 26 4
gpt4 key购买 nike

我正在尝试使用一个函数来读取 csv 文件并返回它。但不幸的是我得到了一个空字符串

function getStations() {

var final_results = [];

$.ajax({
type: "GET",
url: "CSV.csv",
dataType: "text",
success: function (data) {
var lines = data.split(/\r\n|\n/);

//Set up the data arrays
var stations_data = [];

//var headings = lines[0].split(','); // Splice up the first row to get the headings
for (var j = 1; j < lines.length; j++) {
var values = lines[j].split(','); // Split up the comma seperated values
// We read the key,1st, 2nd and 3rd rows

// tmp_data.push(parseFloat(values[0]));
//tmp_data.push(parseFloat(values[1]));
//tmp_data.push(parseFloat(values[2]));
//tmp_data.push(values[4]);
stations_data.push(values[4]);
final_results.push(values[4]);
}

console.log("inside:" + final_results.length)
}
});

// Let's process the data from the data file
console.log("outside: " + final_results.length);
}

结果如下: console.log results

有什么建议吗?

最佳答案

console.log('outside..语句在 ajax 完成之前执行。当 final_results 出现时,您将必须执行某种回调。已加载。

function getStations(callback) {

var final_results = [];

$.ajax({
type: "GET",
url: "CSV.csv",
dataType: "text",
success: function (data) {
var lines = data.split(/\r\n|\n/);

//Set up the data arrays
var stations_data = [];

//var headings = lines[0].split(','); // Splice up the first row to get the headings
for (var j = 1; j < lines.length; j++) {
var values = lines[j].split(','); // Split up the comma seperated values
// We read the key,1st, 2nd and 3rd rows

// tmp_data.push(parseFloat(values[0]));
//tmp_data.push(parseFloat(values[1]));
//tmp_data.push(parseFloat(values[2]));
//tmp_data.push(values[4]);
stations_data.push(values[4]);
final_results.push(values[4]);
}

callback(final_results)
}
});
}

getStations(function (final_results){
console.log("outside: " + final_results.length);
})

关于javascript读取csv文件返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47478766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com