我使用JavaScript代码读取CSV文件,我想将其推入2D数组,以进行一些处理
var dataArray = new Array;
function parseCSV(dataArray) {
//replace UNIX new lines
data = data.replace(/rn/g, "n");
//replace MAC new lines
data = data.replace(/r/g, "n");
//split into rows
var rows = data.split("n");
// loop through all rows
for (var i = 0; i < rows.length; i++) {
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
var date=column[0];
var value = column[4];
// create object which contains all these items:
var dataObject = {
date: date,
T4: value
};
dataArray.push(dataObject);
}
}
}
}
作为测试,我尝试读取一个单元格内容并在网页上显示以验证我读取文件。
<script type="text/javascript">
var x= dataArray[1][4];
document.write(x);
</script>
但没有显示任何东西。任何人都可以帮助??
var dataArray = new Array;
var data = "Date,Description,Created By,Modified By,T4 Tagn";
data += "20170424,This is record 1,user1,none,Just work please.n";
data += "20170424,This is record 2,user2,none,I'm trying too.n";
function parseCSV(dataArray) {
//replace UNIX new lines
data = data.replace(/rn/g, "n");
//replace MAC new lines
data = data.replace(/r/g, "n");
//split into rows
var rows = data.split("n");
// loop through all rows
for (var i = 0; i < rows.length; i++) {
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
var date=column[0];
var value = column[4];
// create object which contains all these items:
var dataObject = {
date: date,
T4: value
};
dataArray.push(dataObject);
}
}
}
parseCSV(dataArray);
缺少文件,我将一些CSV数据强加于以进行处理的字符串中。您的问题没有显示这两个项目:
- 您如何设置 var Data
- 您如何调用 parsecsv(dataarray(
如果出现这两件事都应该起作用 - 这是证明
就HTML脚本部分而言:
您的数组地址看起来不错 - 看来应该看起来像:
<script>
var x = dataArray[1].T4;
document.write(x);
</script>
这是我的推理:
我了解您将CSV数据传递给此功能,以将其解析到您的数据阵列变量中 - 正确吗?
如果正确,此数据看起来像我手动添加的内容(我直接添加了此数据只是为了使用某些东西(。
较大的项目并不是数据来自的位置,但最终它会被此ParseCSV函数所解析。
发生这种情况时,您将以以下方式构建附加到空的 dataArray 变量:
对于第一次通过,这将如下:
[{" date":" date"," t4":" t4 tag"}]
第二次通过:
[{" date":" date"," t4":" t4 tag"},{" date":" 20170424"," t4":"请工作。
第三次通过:
[{" date":" date"," t4":" t4 tag"},{" date":" 20170424"," t4":"请工作。"},{" date":"20170424"," t4":" i 'M也尝试。"}]
所以现在,当您在html 中时,您没有地址的键 [4] 。
您的代码说:
var x = dataArray[1][4];
考虑以下内容以查看我的意思:
var record = dataArray[1];
//{"date" : "20170424", "T4" : "Just work please."}
//There is no key 4 here only date & T4.
var date = record.date;//returns: "20170424"
var t4 = record.T4;//returns: "Just work please."
相比 希望这可以清楚地解释。myObj = {"date" : "20170424", "4" : "This is a value for field 4", "T4" : "Just work please."}
myObj[4];//returns "This is a value for field 4";
这是负载CSV文件函数
function loadCSV(file) {
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(dataArray);
}