簡體   English   中英

逐行讀取文本文件並選擇隨機行javascript

[英]Read text file line by line and select random line javascript

我正在嘗試讀取文本文件filepath = "data/words.txt"並隨機選擇要在控制台中打印的行。

我試着做:

function generateRandomWord() {
  var file = new File(filepath);
  let fileReader = new FileReader();
  const data = fileReader.readAsText(file);
  var lines = data.split("\n");

  var line = lines[Math.floor(Math.random() * lines.length)]; //select a random line from txt file (a random word)
  console.log(line);
}

但是,我似乎無法讀取文件。

如果您想從需要運行代碼的路徑讀取文本文件,例如 node.js 環境; 但如果您使用 HTML 和瀏覽器從輸入中選擇文件,請繼續。

添加一些 html 元素來選擇文件並從選擇的文件中生成文本:

<input type="file" onchange="FileReader(this.files[0])" />
<button onclick="RandomText(TEXT)">Generate</button>

現在添加這個 js 腳本:

var TEXT = "";
async function FileReader(file) {
  TEXT = await file.text();
}
function RandomText(text) {
  const textArray = text.split("\n");
  const randomKey = Math.floor(Math.random() * textArray.length);
  console.log(textArray[randomKey]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM