从2个不同的文件读取为二维数组Javascript

问题描述 投票:1回答:1

如何读取两个.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数组中。怎么做?

谢谢

javascript arrays node.js
1个回答
0
投票

读取文件并将结果推入该变量后,您可以在顶部使用一个空数组作为变量,如下所示:

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

© www.soinside.com 2019 - 2024. All rights reserved.