[英]Splitting a .txt file into a JavaScript Array using FileReader.readAsText()
I've used FileReader.readAsText() to import a file and import it into my array, but it creates a new array that ends up pushing into the first position of my existing array.我使用 FileReader.readAsText() 导入文件并将其导入我的数组,但它创建了一个新数组,最终推入我现有数组的第一个 position。 When I try to index that array it apparently is "undefined" even though I can clearly see the value in my console.log command.
当我尝试索引该数组时,它显然是“未定义的”,即使我可以清楚地看到我的 console.log 命令中的值。 My test.txt file reads
我的 test.txt 文件读取
aaa啊啊啊
bbb bbb
ccc ccc
ddd ddd
eee eee
ddd ddd
eee eee
eee eee
I want to read the file and store it into an array by splitting each line '''我想读取文件并通过拆分每一行'''将其存储到一个数组中
var guestList = []
document.getElementById('inputfile')
.addEventListener('change', function loadFile() {
var fr=new FileReader();
fr.onload=function(){
guestList.push(fr.result.split('\n'));
}
console.log(guestList)
fr.readAsText(this.files[0]);
})
console.log(guestList)
''' Here is what my console looks like: [] 0: (9) ["aaa", "bbb", "ccc", "ddd", "eee", "ddd", "eee", "eee", ""] length: 1 proto : Array(0) ''' 这是我的控制台的样子: [] 0: (9) ["aaa", "bbb", "ccc", "ddd", "eee", "ddd", "eee", "eee" , ""] 长度: 1原型: Array(0)
You're only pushing a single item to the guestList
- the result of splitting the file.您只是将单个项目推送到
guestList
- 拆分文件的结果。 Instead, just use the result of the .split
, instead of surrounding it in another array - and make sure to log the results inside the callback, not outside.相反,只需使用
.split
的结果,而不是将其包围在另一个数组中 - 并确保将结果记录在回调内部,而不是外部。
Also, for multi-system compatibility, some environments use line feed characters as well as newlines.此外,为了多系统兼容性,某些环境使用换行符和换行符。 Consider using a regular expression instead, to optionally match a linefeed followed by a newline:
考虑改用正则表达式,以可选地匹配换行符后跟换行符:
document.getElementById('inputfile').addEventListener('change', () => {
const fr = new FileReader();
fr.onload = () => {
const guestList = fr.result.split(/\r?\n/);
console.log(guestList);
};
fr.readAsText(this.files[0]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.