[英]Javascript create array from local file.txt
I have this text file in the same directory with my javascript program:我在与我的 javascript 程序相同的目录中有这个文本文件:
test.txt测试.txt
1
2
3
4
5
I want to load the data in array.我想加载数组中的数据。 So at the end i will have a array variable as follow:所以最后我会有一个数组变量,如下所示:
[1,2,3,4,5]
This is your text as a string when you get a text file:这是您获取文本文件时作为字符串的文本:
var text = "1\n2\n3\n4\n5";
You need to use String.prototype.split to create an array:您需要使用String.prototype.split创建一个数组:
text = text.split("\n");
After you will get an array:之后你会得到一个数组:
console.log(text); // [1,2,3,4,5]
You can use XMLHTTPRequest to load the text from file, like jQuery does, then you can put it something like this:您可以使用 XMLHTTPRequest 从文件中加载文本,就像 jQuery 一样,然后您可以将其放置如下:
var array = [];
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var text = xmlhttp.responseText;
// Now convert it into array using regex
array = text.split(/\n|\r/g);
}
}
xmlhttp.open("GET", "test.txt", true);
xmlhttp.send();
this way you will get in array
form, the text from test.txt file.通过这种方式,您将获得array
形式的 test.txt 文件中的文本。
I am assuming test.txt in same folder as script does我假设 test.txt 与脚本位于同一文件夹中
try this way试试这个方法
<script>
fs.readFile('test.txt',"utf-8",function(err,data){
if(err) throw err;
var array = Array.from(data) //convert char array
console.log(array)
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.