在使用Node.js的JavaScript中,我无法加入全局数组。
test.csv
最终包含c,d
var placeName = ["a","b"];
var csvFile = 'test.csv';
fs.readFile(csvFile, 'UTF-8', function(err, csv) {
$.csv.toArrays(csv, {}, function(err, data) {
for(var i=0, len=data.length; i<len; i++) {
console.log(data[i]); //Will print every csv line as a newline
placeName.push(data[i][0].toString());
}
});
console.log(placeName); //Inside the function the array show a,b,c,d
});
// Prints only a and b. Did not add c & d from the csv.
console.log(placeName);
答案 0 :(得分:1)
这是因为JavaScript的异步行为。在您阅读CSV文件之前执行console.log(placeName)
外部。