从文本中获取数组

Getting array from text

本文关键字:数组 获取 文本      更新时间:2023-09-26

我一直在试验这段代码 http://mounirmesselmeni.github.io/2012/11/20/javascript-csv/从文本文件中获取数据。(此处的工作演示:http://mounirmesselmeni.github.io/html-fileapi/)。

它适用于读取文件,但我对如何将数据放入数组感到困惑。似乎它正在将所有内容读取到"lines"数组中,但我无法弄清楚如何使用它。

我尝试像这样修改它:

function processData(csv) {
var allTextLines = csv.split(/'r'n|'n/);
var lines = [];
var myArray = [];                      
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
myArray.push(allTextLines.shift().split(','));   //put data into myArray
}
function myFunction() {                          //display myArray in "demo"
var index;
for (index = 0; index < myArray.length; index++) {
    text += myArray[index];
}
document.getElementById("demo").innerHTML = text;
}

但这没有用。我知道我在这里错过了一些简单的东西,但这让我难倒了。

目前,您修改数组两次:

lines.push(allTextLines.shift().split(','));     // shift modifies the array
myArray.push(allTextLines.shift().split(','));   //gets the shifted array

你可能想尝试把它放在临时变量中:

var line = allTextLines.shift().split(',');
lines.push(line);
myArray.push(line);

尝试

csv.split(/'r'n|'n|,/).map(function(value, index) {
  demo.innerHTML += "'n" + value.trim()
});

var csv = 'Year,Make,Model,Description,Price'
+ '1997,Ford,E350,"ac, abs, moon",3000.00'
+ '1999,Chevy,"Venture ""Extended Edition""","",4900.00'
+ '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00'
+ '1996,Jeep,Grand Cherokee,"MUST SELL!'
+ 'air, moon roof, loaded",4799.00',
    demo = document.getElementById("demo");
csv.split(/'r'n|'n|,/).map(function(value, index) {
  demo.innerHTML += "'n" + value.trim()
})
<div id="demo"></div>