如何读取两个 .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])
})
我成功地将文件存储在一维数组中,但现在我有 2 个文件,我想将它们存储在二维数组中。 如何做到这一点?
谢谢
最佳答案
在读取文件并将结果推送到该变量后,您可以在顶部有一个带有空数组的变量,如下所示:
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 个不同的文件读取为二维数组 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59357602/