我想使用JavaScript在数组中仅存储marks
个值。
这是我的代码:
<html>
<head>
<script type = "text/javascript">
function Upload() {
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var lines = e.target.result.split("\n");
var resul = [];
var headers = lines[0].split("\t");
for (var i = 0; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
headers[j] = currentline[j];
}
resul.push([i, obj]);
document.write(" " + resul);
}
return resul;
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
</script>
</head>
<body>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick = "Upload()" />
<hr />
</body>
</html>
问题是我得到的输出如下:
0,
[object Object] 0,
[object Object],
1,
[object Object] 0,
[object Object],
1,
[object Object],
2,
[object Object] 0,
[object Object],
1,
[object Object],
2,
[object Object],
3,
[object Object] 0,
[object Object],
1,
[object Object],
2,
[object Object],
3,
[object Object],
4,
[object Object] 0,
[object Object],
1,
[object Object],
2,
[object Object],
3,
[object Object],
4,
[object Object],
5,
[object Object] 0,
[object Object],
1,
[object Object],
2,
[object Object],
3,
[object Object],
4,
[object Object],
5,
[object Object],
6,
[object Object] 0,
[object Object],
1,
[object Object],
2,
[object Object],
3,
[object Object],
4,
[object Object],
5,
[object Object],
6,
[object Object],
7,
[object Object]
我希望输出为:
[1, 20.248602],
[2, 18.54032],
… etc.,
但我没有得到我做错的地方。我该如何解决?请帮忙。
这是CSV
文件,其中包含:
name,marks,rank
a,20.248602,a+
b,18.54032,ko+
c,18.254036,ko+
d,15.217833,ok
e,13.194518,b-
f,17.521723,ko-
答案 0 :(得分:0)
请修改你的for循环:
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
resul.push([i, currentline[1]]);
}
document.write(" " + resul.join());
就输出问题而言,不需要任何嵌套的for循环