如何读取两个.txt文件并将这两个文件转换为二维数组?
我已经有这样的代码:
var fs = require('fs')
file = './text1.txt'
fs.readFile(file,'utf-8', (e,d) => {
textByLine = d.split('\r\n');
console.log("test : " + textByLine[1])
})
source
我成功地将文件存储在一个1d数组中,但是现在我有2个文件,我想将它们存储在2d数组中。
这该怎么做?
谢谢
最佳答案
在读取文件并将结果推入该变量之后,可以在顶部使用一个空数组作为变量,如下所示:
const 2dArray = [];
const fillArray = (path)=> {
fs.readFile(path,'utf-8', (e,d) => {
2dArray.push(d.split('\r\n')) // the result is already an array.
});
});
之后,您可以像这样调用每个文件:
// read the files and push the result to the variable 2dArray
fillArray('./text1.txt');
fillArray('./text2.txt');
//you can read the 1st result of your 1st file array like this
const firstPartOfArray = 2dArray[0][0]; // text1 first result value
如果您不需要顺序生成结果文件,我强烈建议您使用异步功能。
您也可以使用fs-jetpack package之类的思想来解决这个问题,或者glob
关于javascript - 从2个不同的文件读取为2维数组Javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59357602/