繁体   English   中英

如何将本地文本文件读取到本地html并将内容读取到javascript的二维数组?

[英]How to read a local text file to a local html and read the content to a two dimensional array for javascript?

如何将本地文本文件读取到本地 html 并将内容读取到 javascript 数组?

<html>
<head>
<script>
window.onload = function () {
    document.getElementById('myfile').onchange = readFile;
};
function readFile() {
    file = this.files[0];
    var fReader = new FileReader();           
    fReader.onload = function (event) {
        document.getElementById('fileContent').value = event.target.result;
    };
    fReader.readAsText(file);
}
</script>
</head>
<body>
    <p> <input id="myfile"  type="file"     /></p>
    <textarea  id="fileContent" cols="68" rows="10"  ></textarea>
</body>
</html>

它可以读取文本文件并打印在 html 上。

但是如何在javascript中转换为数组呢?

我想要的javascript中的数组是这样的:

<script type="text/javascript"> 
   var dataset = [
        [0,619804,7,128],
        [1,638224,6327,128],
        [2,639157,12342,64],
        [1,639157,6440,64],
        [3,645597,173,21],
        [4,645597,150,21],
        [5,645597,301,22],
        [6,645747,12153,17],
        [7,645898,15367,47],
        [8,646393,7650,22],
        [9,646393,321,21],
        [10,646393,18049,21],]
</script>

如果我猜你的文本文件是这种形式:

8,646393,7650,22
9,646393,321,21
10,646393,18049,21
...

所以你只需要用 \\r\\n 拆分即可转换为数组。

var resultText = event.target.result;
var array = resultText.split('\r\n');

我有一个这样的数组:

[
  "8,646393,7650,22",
  "9,646393,321,21",
  "10,646393,18049,21"
]

所以如果你想把它转换成你的数组类型,你只需要:

var newArray = [];    
for (var i = 0, max = array.length; i < max; i++) {
   newArray.push([array[i]])
}

你应该有这个:

[
  [
    "8,646393,7650,22"
  ],
  [
    "9,646393,321,21"
  ],
  [
    "10,646393,18049,21"
  ]
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM