使用索引方法推送到数组(JavaScript)

时间:2013-09-01 18:10:17

标签: javascript arrays push

我很难通过索引将对象推送到数组数组。在下面找到我当前(非常重复的代码),它读取CSV文件的行(格式:日期,reasonCode),然后根据reasonCode创建FROM和TO(日期)对。然后将该数组用于Highcharts(甘特图)。请注意fromto1fromto2数组。

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,在其他主题上找不到任何答案,我们非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您的JavaScript中有很多内容可以提供有关如何使用最佳做法执行操作的一些提示,以及答案+建议。

1)单个声明中的多个变量用逗号分隔,而不是半冒号:

var csv = csv.split(/\n/g),
    fromto = [],
    count = [],
    lastFrom = [];

2)不要使用Array对象来制作数组。

fromto.push([]);

3)如果使用var,JS的功能范围。如果没有var,变量就是全局的。

jQuery.each(csv, function(i, line) {
  line = line.split(',');
  var date = parseInt(line[0], 10)*1000,
      reasonC = parseInt(line[2], 10);

4)==是一个强制相等,并且会看到是否有任何方式两个值可以被认为是相同的。 4 ==“4”为真,4 ===“4”不是。

if (reasonC == c) { ...

if (reasonC === c.toString()) { ...

5)JavaScript有forEach烘焙,为什么你会使用jQuery作为JavaScript的一部分呢?

csv.forEach(function(line) {
  ...
});

然后是你问题的答案。看起来你正试图改变这些数据:

123,somevalue,1
456,somevalue,2
...

进入这个结构:

[
  { from: 123, to: 456 },
  { from: ..., to: ...},
  ...
] 

您依靠行顺序告诉您哪个日期是来自哪个日期是哪个日期;这肯定会出错,但你最了解你的数据。 (如果我写这篇文章,我会假设行排序未知)

var cvs = data.split(",");
    parity = 0,
    fields,
    odd = [],
    even = [],
    fromTo = [];

cvs.forEach(function(line) {
  parity = (parity + 1) % 2;
  fields = line.split(",");
  bin = parseInt(fields[2],10);
  if(parity===1) {
    odd[bin] = fields;
  } else {
    even[bin] = fields;
    fromTo[bin].push({
      from: odd[bin][0],
      to: even[bin][0]
    });
  }
});

现在,这应该可以工作,但是这段代码也非常可怕,因为它仍然依赖于CVS文件中的行排序,并且没有硬保证这种情况(如预处理验证),这(就像你的代码一样)在两条线路意外错误的情况下,它会做出可怕的错误。