javascript – 读取制表符分隔文件,逐行比使用制表符分隔每行分割

前端之家收集整理的这篇文章主要介绍了javascript – 读取制表符分隔文件,逐行比使用制表符分隔每行分割前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我能够逐行读取文件,但我不知道如何使用制表符分隔每行.这是我的代码.需要一些关于这个问题的帮助
  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head>
  3. <title>Sum of a Column in JavaScript</title>
  4. </head>
  5.  
  6. <input type="file" name="file" id="file">
  7.  
  8. <script type="text/javascript">
  9.  
  10. document.getElementById('file').onchange = function(){
  11.  
  12. var file = this.files[0];
  13.  
  14. var reader = new FileReader();
  15. reader.onload = function(progressEvent){
  16. // Entire file
  17. console.log(this.result);
  18.  
  19. // By lines
  20. var lines = this.result.split('\n');
  21. for(var line = 0; line < lines.length; line++){
  22. // By tabs
  23. var tabs = lines[line].split('\\t');
  24. for(var tab = 0; tab < tabs.length; tab++){
  25. alert(tabs[tab]);
  26. }
  27. }
  28. };
  29. reader.readAsText(file);
  30. };
  31.  
  32. </script>

解决方法

我发现这很有用,并用js .map()函数替换了for …循环.另外,我将数据加载到数组中:
  1. // By lines
  2. var arr1 = [];
  3. var arr2 = [];
  4. var arr3 = [];
  5. var arr4 = [];
  6. var arr5 = []; // assuming 5 tabs
  7. var lines = this.result.split('\n');
  8. lines.map(function(item){
  9. var tabs = item.split('\t');
  10. console.log("0",tabs[0],"1",tabs[1],"2",tabs[2],"3",tabs[3],"4",tabs[4],"5",tabs[5],"6",tabs[6]);
  11. arr1.push(tabs[0]);
  12. arr2.push(tabs[1]);
  13. arr3.push(tabs[2]);
  14. arr4.push(tabs[3]);
  15. arr5.push(tabs[4]);
  16. });
  17. // test two of the arrays after reading:
  18. for (var i = 0; i < mdarr.length; i++) {
  19. console.log(arr1[i],arr2[i]);
  20. };
  21. }
  22. reader.readAsText(file);
  23. };

猜你在找的JavaScript相关文章