我很难通过索引将对象推送到数组数组。在我当前的(非常重复的代码)下面找到它读取 CSV 文件的行(格式:日期,reasonCode),然后根据 reasonCode 创建 FROM 和 TO(日期)对。然后将该数组用于 Highcharts(甘特图)。请注意fromto1
andfromto2
数组。
csv = csv.split(/\n/g);
var fromto1 = []; //array of FROM and TO pairs of code 1
fromto2 = []; //array of FROM and TO pairs of code 2
count = [];
lastFrom = [];
for (var i=1;i<3;i++) { //set all count and lastFrom variables to 0 //bs
count[i] = 0;
lastFrom[i] = 0;
}
jQuery.each(csv, function(i, line) {
line = line.split(','); //splits line, returns array of splitted values
date = parseInt(line[0], 10)*1000; //read date from line into string
reasonC = parseInt(line[2], 10); //read reasonC from line into string
if (reasonC == "1") {
count[1]++;
if (count[1] % 2 !=0){ //if it is an uneven value (FROM values)
lastFrom[1] = date; //temporary save the date in lastFrom[]
}
else { //if it is an even value (TO value), push the pair
fromto2.push({
from: lastFrom[1],
to: date
});
}
}
if (reasonC == "2") {
count[2]++;
if (count[2] % 2 !=0){
lastFrom[2] = date;
}
else {
fromto3.push({
from: lastFrom[2],
to: date
});
}
}
为什么我不能用这个替换上面的代码(请注意fromto
数组的数组):
csv = csv.split(/\n/g);
var fromto = [];
count = [];
lastFrom = [];
for (var i=1;i<3;i++) { //set all count and lastFrom variables to 0
count[i] = 0;
lastFrom[i] = 0;
fromto.push(new Array());
console.log(i+': New Array Pushed');
}
jQuery.each(csv, function(i, line) {
line = line.split(','); //splits line, returns array of splitted values
date = parseInt(line[0], 10)*1000; //read date from line into string
reasonC = parseInt(line[2], 10); //read reasonC from line into string
for (var c=1;c<3;c++) {
if (reasonC == c.toString()) {
count[c]++;
if (count[c] % 2 !=0){ //if it is an uneven value (FROM values)
lastFrom[c] = date; //temporary save the date in lastFrom[]
}
else { //if it is an even value (TO value), push the pair
fromto[c].push({
from: lastFrom[c],
to: date
});
}
}
}
}
我相信问题在于fromto[c].push({
它保持空白数组。我仍然是一个 Jsnoob,在其他线程上找不到任何答案,非常感谢您的帮助