我正在尝试使用NodeJS从数组中的文本文件中存储X和Y值,但实际上我并不知道如何做到这一点。
文本文件如下所示:
X Y
385 0.12567
386 0.25786
387 0.35789
388 0.45798
... .......
所以我试图让Arrays看起来像那样:
arr[x]= 385, 386, 387, 388 ...
arr[y]= 0.12567, 0.25786, 0.35789, 0.45798 ..
我希望你能帮助我!
JS
答案 0 :(得分:2)
你可以这样做:
var fs = require('fs');
function readLines(input, done) {
var arr = [];
var remaining = '';
input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
while (index > -1) {
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});
input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
done(arr);
}
});
function func(data) {
arr.push(data.split(/\s+/g));
}
}
var input = fs.createReadStream('test.txt');
readLines(input, done);
function done(arr) {
var obj = {};
var key1 = arr[0][0];
var key2 = arr[0][1];
obj[key1] = [];
obj[key2] = [];
arr.shift();
arr.forEach(function (item) {
obj[key1].push(item[0]);
obj[key2].push(item[1]);
});
console.log('X:', obj['X']);
console.log('Y:', obj['Y'])
}
输出:
X: [ '385', '386', '387', '388' ]
Y: [ '0.12567', '0.25786', '0.35789', '0.45798' ]
请参阅: node.js: read a text file into an array. (Each line an item in the array.)