【问题标题】:I want to read a certain amount of lines from a text file, and with them to create an object after reading the lines using JavaScript我想从文本文件中读取一定数量的行,并在使用 JavaScript 读取行后与它们一起创建一个对象
【发布时间】:2021-08-25 10:50:18
【问题描述】:

好的,这是我的要求:应用程序必须从文本文件中读取每一行。可以使用一个类,以便在读取一定数量的行之后创建一个对象(这样应用程序的结构更加清晰)。读取一个学生数据对应的数据集后,会将该数据集添加到一个字符串中(分开以便连续显示)。

所以我有 2 名学生的这些信息,如下图所示,一个在另一个之下,但没有姓名地址等(这里显示不正确)。

乌木兰格尔 育空街 7175 号 (507) 833-3567 地理 基南·埃尔伍德 2榆树巷 (894) 831-6482 历史

在那个文件中。在阅读每一行之后,我应该在第一行前面添加名称,在第二行前面添加地址..电话和课程等等。 结果应如下所示:

这就是我现在所拥有的(我必须使用 Fetch 来获取文件,异步和等待。或者使用 Promise)

let button = document.getElementById("text-button");
let textArea = document.getElementById("text-area");

button.addEventListener("click", function () {
  getData();
});

//cod fetch
async function getData() {
  try {
    let response = await fetch('fileName.txt');
    if (response.status !== 200) {
      throw new Error("Error while reading file");
    }
    let text = await response.text();
    textArea.innerHtml = text;
  } catch (err) {
    textArea.innerHTML = 'Problem occurred: ' + err.message;
  }
}

请帮忙!我一直被困在这个问题上。

【问题讨论】:

    标签: javascript arrays async-await promise fetch


    【解决方案1】:

    由于您是从 .txt 文件中提取的,我认为了解文件中使用的换行符很重要。这是我发现的一个不错的链接,它在文章顶部说明了您所需要的一切:End of Line or Newline Characters

    我按照文章推荐的方式在 Notepad++ 中打开了 .txt 文件,看到了这个:

    每行后面显示的 [CR][LF] 表示使用的换行符是\r\n。

    当你明白你意识到你可以在每个换行符处使用这些换行符来分隔你的字符串。

    这是 String.split() String.prototype.split() 的 MDN

    String.split('\r\n') 将返回 Array 的项目,特别是 在之间但不包括\r\n字符的字符串。

    让我们将其添加到getData 函数中:

    let button = document.getElementById("text-button");
    let textArea = document.getElementById("text-area");
    
    button.addEventListener("click", function () {
      getData();
    });
    
    //cod fetch
    async function getData() {
      try {
        let response = await fetch('fileName.txt');
        if (response.status !== 200) {
          throw new Error("Error while reading file");
        }
        let text = await response.text();
        
        //New stuff:
        let arrayOfText = text.split('\r\n');
        //Now we could add what we want before the text.
        //We need to do every 4 lines so lets use this as a chance to learn % better
        arrayOfText = arrayOfText.map((textItem, index) => {
            let remainder = (index) % 4        //This will return 0, 1, 2, 3
    
        //switch but you could use anything
            switch (remainder) {
                case 0:
                    textItem = 'Name: ' + textItem + '\r\n';
                    break;
                case 1:
                    textItem = 'Address: ' + textItem + '\r\n';
                    break;
                case 2:
                    textItem = 'Phone: ' + textItem + '\r\n';
                    break;
                case 3:
                    textItem = 'Course: ' + textItem + '\r\n\r\n';    //two here to separate the groups
                    break;
            //we need a default so lets make it just return textItem if something goes wrong
                default:
                    break;
    
            };
    
            //Our new array has all the info so we can use 
            //Array.prototype.join('') with an empty string to make it a string.
            //We need those old line breaks though so lets put them 
            //in the switch returns above.
        
            text = arrayOfText.join('');
    
            //End of my changes/////////////
    
        textArea.innerHtml = text;
      } catch (err) {
        textArea.innerHTML = 'Problem occurred: ' + err.message;
      }
    }
    

    我希望这对你有用。它不是最迷人的解决方案,但它是一个很好的学习解决方案,因为它只使用您在学习早期学到的东西。

    如果我能澄清任何事情,请告诉我!

    【讨论】:

      【解决方案2】:
      async function getData() {
        try {
          let response = await fetch('https://v-dresevic.github.io/Advanced-JavaScript-Programming/data/students.txt');
          if (response.status !== 200) {
            throw new Error("Error while reading file");
          }
          let text = await response.text();
          const lines = text.split('\n');
          const CHUNK_SIZE = 4;
          textArea.innerHTML = new Array(Math.ceil(lines.length / CHUNK_SIZE))
            .fill()
            .map(_ => lines.splice(0, CHUNK_SIZE))
            .map(chunk => {
              const [Name, Address, Phone, Course] = chunk;
              return {Name, Address, Phone, Course};
            })
            .reduce((text, record) => {
              text += Object.keys(record).map(key => `${key} ${record[key]}`).join('\n') + '\n';
              return text;
            }, '');
      
        } catch (err) {
          textArea.innerHTML = 'Problem occurred: ' + err.message;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-24
        • 1970-01-01
        • 1970-01-01
        • 2016-08-16
        • 1970-01-01
        相关资源
        最近更新 更多