我能够逐行读取文件,但我不知道如何使用分隔符分隔每行.我的代码.需要一些关于这个问题的帮助
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sum of a Column in JavaScript</title>
</head>
<input type="file" name="file" id="file">
<script type="text/javascript">
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
// By tabs
var tabs = lines[line].split('\\t');
for(var tab = 0; tab < tabs.length; tab++){
alert(tabs[tab]);
}
}
};
reader.readAsText(file);
};
</script>
Run Code Online (Sandbox Code Playgroud)
Mag*_*edt 12
我发现这很有用,并用js .map()函数替换了for ...循环.另外,我将数据加载到数组中:
// By lines
var arr1 = [];
var arr2 = [];
var arr3 = [];
var arr4 = [];
var arr5 = []; // assuming 5 tabs
var lines = this.result.split('\n');
lines.map(function(item){
var tabs = item.split('\t');
console.log("0",tabs[0], "1",tabs[1], "2",tabs[2],"3", tabs[3],"4", tabs[4], "5", tabs[5], "6", tabs[6]);
arr1.push(tabs[0]);
arr2.push(tabs[1]);
arr3.push(tabs[2]);
arr4.push(tabs[3]);
arr5.push(tabs[4]);
});
// test two of the arrays after reading:
for (var i = 0; i < mdarr.length; i++) {
console.log(arr1[i], arr2[i]);
};
}
reader.readAsText(file);
};
Run Code Online (Sandbox Code Playgroud)
这可以用一个衬垫来完成。首先按换行符拆分,然后按制表符拆分。结果是一个二维数组,其中第一项是标题行。
const parsedString = tabbedString.split('\n').map((line) => line.split('\t'))
Run Code Online (Sandbox Code Playgroud)
const tabbedString = `Prefix Name Last Name Email Phone Age Role
Jim Loco jilo@fox.com 32 Admin
Mrs. Sara Foo safoo@fox.com 124389 44 Admin
Mr. John Deer jodeer@fox.com 37 Developer`
const parsedString = tabbedString.split('\n').map((line) => line.split('\t'))
console.log(parsedString)
Run Code Online (Sandbox Code Playgroud)
[
[
"Prefix",
"Name",
"Last Name",
"Email",
"Phone",
"Age",
"Role"
],
[
"",
"Jim",
"Loco",
"jilo@fox.com",
"",
"32",
"Admin"
],
[
"Mrs.",
"Sara",
"Foo",
"safoo@fox.com",
"124389",
"44",
"Admin"
],
[
"Mr.",
"John",
"Deer",
"jodeer@fox.com",
"",
"37",
"Developer"
]
]
Run Code Online (Sandbox Code Playgroud)
请注意,堆栈溢出将制表符替换为 4 个空格,因此在输入字符串中您实际上会找到 4 个空格而不是制表符,但在我的原始代码中它们确实是制表符。
| 归档时间: |
|
| 查看次数: |
26991 次 |
| 最近记录: |