长话短说:我必须使用JavaScript从.csv文件中读取数据,并且我有一个函数用数据填充我的全局定义数组(=每个数组的条目是一个新的对象)。
问题是我只能通过函数内部的索引访问数组(console.log(requestors [0] .ID);)并且我需要在函数外部访问它,所以我可以修改/使用它。 / p>
我做错了什么?
非常感谢!
var requestors = [];
class Requestor {
constructor(ID, RequestorName, RequestorSurname, RequestorGivenname, RequestorUID, RequestorEmail, Location, Department) {
this.ID = ID;
this.RequestorName = RequestorName;
this.RequestorSurname = RequestorSurname;
this.RequestorGivenname = RequestorGivenname;
this.RequestorUID = RequestorUID;
this.RequestorEmail = RequestorEmail;
this.Location = Location;
this.Department = Department;
}
}
$(document).ready(function() {
$.ajax({
type: "GET",
url: "./app/csv/requestors.csv",
dataType: "text",
success: function(data) {
processRequestors(data);
}
});
});
var h = 0;
function processRequestors(allRequestorsEntries) {
var allRequestorsRows = allRequestorsEntries.split(/\r\n|\n/);
var headers = allRequestorsRows[0].split(',');
for (var i = 1; i < allRequestorsRows.length; i ++) {
var data = allRequestorsRows[i].split(',');
if (data.length === headers.length) {
requestors[h] = new Requestor();
for (var j = 0; j < headers.length; j ++) {
requestors[h][headers[j]] = data[j];
}
h ++;
}
}
console.log(requestors[0].RequestorName); // value
}
console.log(requestors[0].RequestorName); // undefined