简体   繁体   English

Javascript循环创建数组数组(不遍历数组数组)

[英]Javascript loop to create array of arrays (not loop through array of arrays)

I am trying to loop through two arrays of dates, dateFrom and dateTo to use in a gantt chart plugin. 我试图遍历两个日期数组dateFromdateTo以在甘特图插件中使用。 The gantt chart requires ganttData . 甘特图需要ganttData I want to loop through these two arrays simultaneously and create ganttData as an array of arrays. 我想同时遍历这两个数组,并将ganttData创建为数组数组。 Right now, it is looping simultaneously through both arrays but ganttData is only the last index of both arrays, which makes sense because I am just reassigning the values each time through the loop. 现在,它同时在两个数组中循环,但是ganttData只是两个数组的最后一个索引,这是有道理的,因为我每次都在循环中重新分配值。

I tried using += instead of = but I get an error: 我尝试使用+=代替=但出现错误:

Uncaught TypeError: Cannot read property 'length' of undefined 未捕获的TypeError:无法读取未定义的属性“ length”

Below is the code that I have so far: 以下是我到目前为止的代码:

These arrays are correct Ive checked. 我已经检查了这些数组是否正确。

I am unfamiliar with JS so any and all help is greatly appreciated. 我不熟悉JS,因此非常感谢您提供所有帮助。 Thank you! 谢谢!

var datesFrom = <%= dates_from %>
var datesTo = <%= dates_to %>
//var ganttData = [] if I were to use ganttData += [ below 

output = []
i;

for (i = 0; i < (datesFrom.length - 1); i += 1) {
    ganttData = [{
        id: 1, name: "Feature 1", series: [
            { name: "Planned", start: new Date(datesFrom[i]), end: new Date(datesTo[i]) },
            { name: "Actual", start: new Date(datesFrom[i]), end: new Date(datesTo[i]), color: "#f0f0f0" }
        ]
    }];
};  

In general, to build up an array, you'd use this pattern: 通常,要构建一个数组,可以使用以下模式:

var ganttData = [];
for (...) {
  ganttData.push({...});
}

In JavaScript, as opposed to say Ruby, array1 + array2 is not defined: it will convert both arguments to strings and concatenate those instead. 在JavaScript中,与Ruby相比,未定义array1 + array2 :它将两个参数都转换为字符串,然后将其连接起来。 For array concatenation, you need to use array1.concat(array2) , or if you want a destructive method (ie to change array1 ), array1.push.apply(array1, array2) ; 对于数组连接,您需要使用array1.concat(array2) ,或者如果您想要破坏性的方法(即更改array1 ),请使用array1.push.apply(array1, array2) ; but for appending one element, push is a better choice. 但是对于附加一个元素, push是一个更好的选择。

Assuming datesTo and datesFrom are the same length, you'll want to create an array (ganttData) and push a new object to it for each pair of dates, like so: 假设datesTo和datesFrom的长度相同,则需要创建一个数组(ganttData),并为每个日期对将一个新对象推送到该数组,如下所示:

var ganttData = [];

for(var i = 0; i < datesFrom.length; i++) {
  ganttData.push({
    id: i,
    name: "Feature " + i,
    series: [
      { name: "Planned", start: new Date(datesFrom[i]), end: new Date(datesTo[i]) },
      { name: "Actual", start: new Date(datesFrom[i]), end: new Date(datesTo[i]), color: "#f0f0f0" }
    ]
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM