如何使用jQuery动态创建数组

时间:2015-09-08 13:04:33

标签: jquery

我有静态数组。但它是静态格式。我正在尝试动态创建相同的东西。

[
  ['', 'Kia', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'],
  ['2012', 10, 11, 12, 13, 15, 16],
  ['2013', 10, 11, 12, 13, 15, 16],
  ['2014', 10, 11, 12, 13, 15, 16],
  ['2015', 10, 11, 12, 13, 15, 16],
  ['2016', 10, 11, 12, 13, 15, 16]
];

this.getDynamically = function(data) {
    for(var i=0 ; i< data.count ;i++) {
        // here this data will be create one by one row. 
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个:您可以迭代数据并为前7个元素创建数组,并将其放在另一个数组中并将计数器重置为零。再次为接下来的7个元素重复相同的过程。

this.getDynamically = function(data) {
 var a = new Array();
 var b = new Array();
 var count = 0;
 jQuery.each(data, function(i,v){
    b.push(v);
    count++;
    if(count == 7)
    {
      count = 0;
      a.push(b);
      b = new Array();
    }
 });
}

答案 1 :(得分:0)

在循环中使用Array.prototype.push()函数。

var a = [
  ['', 'Kia', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'],
  ['2012', 10, 11, 12, 13, 15, 16],
  ['2013', 10, 11, 12, 13, 15, 16],
  ['2014', 10, 11, 12, 13, 15, 16],
  ['2015', 10, 11, 12, 13, 15, 16],
  ['2016', 10, 11, 12, 13, 15, 16]
];

a.push( ['2017', 10, 11, 12, 13, 15, 16])
console.log(a);