javascript - 从文本中获取数组

标签 javascript arrays filereader

我一直在尝试这段代码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);

关于javascript - 从文本中获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28011302/

相关文章:

php - 如何在PHP函数中使用Mysql数组的行?

java - 如何使频率数组准确地描述解码的 mp3 文件?

python - 打开文件并读取数据

javascript - 如何在 Angular JS 中自定义 $watch?

javascript - 根据输入字段的变化插入值

javascript - 超过26字节的CRC计算

javascript - Angular JSON 仅适用于本地 json 文件,不适用于 url

java - 使用分割和逗号运算符时出现空指针异常错误

java - 读入文件以创建二维数组单词搜索难题并解决

javascript - 垂直居中上传的图像预览