对此有很多解决方案,但我在 html 网页上的 javascript 中发现很少或根本没有。我的html 文件所在的位置有一个名为sample.txt 的数据文件。我的目标是将 txt 文件加载到数组中,该数组可用于创建表格并显示在 html 文件上。我的sample.text 文件具有以下数据:
sin 0.2 time 0.22222
cos 0.3 time 0.43434
tan 0.1 time 0.22221
我是 Javascript 新手,我承认它比其他编程语言更困难。 我熟悉node.js模式下的javascript,但不熟悉html模式。我成功地创建了 html 网页(如下所示)并以脚本模式显示文本和数字等基本信息。我还设法加载 txt 文件并在脚本模式下按下按钮后显示它。这个 txt 加载方法是唯一对我有用的方法。 require(js) 方法不起作用也无法导入。如何从此工作模式创建数据数组?
下面是我的完整代码(已更正),
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Read Text File</title>
</head>
<body>
<input type="file" name="inputfile"
id="inputfile">
<br>
<pre id="output"></pre>
<script>
var file = document.getElementById('inputfile');
file.addEventListener('change', () => {
var txtArr = [];
var fr = new FileReader();
fr.onload = function() {
// By lines
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
txtArr = [...txtArr, ...(lines[line].split(" "))];
}
}
fr.onloadend = function() {
console.log(txtArr);
document.getElementById('output').textContent=txtArr.join("");
document.getElementById("output").innerHTML = txtArr[1];
console.log(txtArr[1]);
}
fr.readAsText(file.files[0]);
})
</script>
</body>
</html>
最佳答案
使用FileReader
,逐行获取字符串,然后将其拆分并合并到resultArr中,如下所示:
var file = document.getElementById('inputfile');
file.addEventListener('change', () => {
var txtArr = [];
var fr = new FileReader();
fr.onload = function() {
// By lines
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
txtArr = [...txtArr, ...(lines[line].split(" "))];
}
}
fr.onloadend = function() {
console.log(txtArr);
document.getElementById('output').textContent=txtArr.join("");
}
fr.readAsText(file.files[0]);
})
<!DOCTYPE html>
<html>
<head>
<title>Read Text File</title>
</head>
<body>
<input type="file" name="inputfile"
id="inputfile">
<br>
<pre id="output"></pre>
</body>
</html>
关于javascript - 如何读取txt文件并将其保存在html中的javascript数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65821206/