【问题标题】:How to push lines from a text file to an array so they can be manipulated later如何将文本文件中的行推送到数组中,以便以后对其进行操作
【发布时间】:2021-02-10 09:06:24
【问题描述】:

我正在尝试加载一个文本文件,逐行读取它,并将其显示在文本区域中。然后我想使用该文本区域中的每一行创建一个新数组,以便以后可以以各种方式操作该数组(例如,根据每行包含的内容过滤内容)。

到目前为止,我已经让它逐行读取文本文件并将其显示在文本区域中,但是当我到达下面的注释部分时,我正在努力弄清楚如何将每一行推到一个新的数组。

let input = document.querySelector("input");
let textArea = document.querySelector("textarea");
let files = input.files;

input.addEventListener("change", () => {
    let files = input.files;

    if (files.length == 0) return;

    const file = files[0];

    let reader = new FileReader();

    reader.onload = function (e) {
        const file = e.target.result;
        const lines = file.split(/\r\n|\n/);
        const content = lines.join('\n');
        textArea.value = content; //trying to create a new array out of each line in this text area
        //could I use a For loop here on each line of the textArea? I am having trouble accessing it line by line
    reader.readAsText(file);

    //I have tried accessing the content variable from here but it says it is undefined.


    }   
);

我在尝试访问函数外部的 content 变量时遇到了麻烦。这和范围有关吗?

【问题讨论】:

    标签: javascript arrays reader


    【解决方案1】:

    你必须使用 div 而不是 textarea

    但是你添加了“contenteditable=true”属性

    https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content

    同时检查 RegExp

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      相关资源
      最近更新 更多