逐行读取Javascript中的.csv文件,并使用while循环将其放入数组中

问题描述 投票:-1回答:1

我之前在C#中做过这个,但我不知道如何在javascript中做到这一点。

我想做的事:

while (/*Is not the last line of the csv file*/)
 {
    var text = /* read the line */
    var split = /* array with the values from the line that was read */

    alert(split[0]);
}

谢谢你的建议!

javascript html arrays csv split
1个回答
0
投票

你的CSV文件存放在某个地方吗?或者你把它存储为字符串?

按照你的结构,这里有一个plunker:https://plnkr.co/edit/dCQ4HRz3mCTkjFYrkVVA?p=preview

var csv = 
`data1,data2,data3
col1,col2,col3`;
var lines = csv.split("\n");
while( typeof lines[0] !== "undefined" ){
    var line = lines.shift();
    var split = line.split(',');
    document.querySelector("#content").innerHTML += split[0]+"<br/>";
}

如果您没有将CSV作为字符串,则根据您是否使用Node在浏览器中读取文件或JavaScript以读取上载的文件,您需要其他代码来转换它。或者您可以使用图书馆。

您可能必须通过修改上面的代码来处理逗号周围的空格修剪。

顺便说一下,有些人可能不喜欢使用while循环而不是创建临时变量:https://plnkr.co/edit/31yMTw9RepdW1cF8I6qj?p=preview

document.querySelector("#content").innerHTML = 
csv.split("\n")        // these are lines
  .map(                // map those lines, 1 line to ...
    l => l.split(",")  // to 1 array
  ).map(
    a => a[0]+"<br/>"  // and map those arrays 1 array to the string
  ).join('');            // and join them to become 1 string

你可能会发现这些数组操作函数很有趣,比如map()filter()reduce()

希望这些帮助!

© www.soinside.com 2019 - 2024. All rights reserved.