push()一个二维数组

时间:2012-07-05 14:01:57

标签: javascript arrays for-loop multidimensional-array push

我正在尝试推送到二维数组而不会弄乱,目前我的数组是:

var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]

我正在尝试的代码是:

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;
var cols = 7;

for (var i = r; i < rows; i++)
{
    for (var j = c; j < cols; j++)
    {
        myArray[i][j].push(0);
    }
}

这应该导致以下结果:

var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
]

但它不会也不确定这是否是正确的方法。

所以问题是如何实现这个目标?

9 个答案:

答案 0 :(得分:38)

您的代码中存在一些错误:

  1. 使用myArray[i].push( 0 );添加新列。您的代码(myArray[i][j].push(0);)可以在三维数组中工作,因为它会尝试将另一个元素添加到位置[i][j]的数组中。
  2. 您只在所有行中展开(col-d) - 多列,即使是那些尚未初始化的列,因此到目前为止还没有任何条目。
  3. 一个正确的,虽然详细的版本,但如下:

    var r = 3; //start from rows 3
    
    var rows = 8;
    var cols = 7;
    
    // expand to have the correct amount or rows
    for( var i=r; i<rows; i++ ) {
      myArray.push( [] );
    }
    
    // expand all rows to have the correct amount of cols
    for (var i = 0; i < rows; i++)
    {
        for (var j =  myArray[i].length; j < cols; j++)
        {
            myArray[i].push(0);
        }
    }
    

答案 1 :(得分:4)

您必须遍历所有行,并添加缺少的行和列。对于已存在的行,从c循环到cols,对于新行,首先将空数组推送到外部数组,然后从0循环到cols:

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;
var cols = 7;

for (var i = 0; i < rows; i++) {
  var start;
  if (i < r) {
    start =  c;
  } else {
    start = 0;
    myArray.push([]);
  }
  for (var j = start; j < cols; j++) {
        myArray[i].push(0);
    }
}

答案 2 :(得分:4)

迭代两个维度意味着您需要检查两个维度。

假设您从以下开始:

var myArray = [
    [1,1,1,1,1],
    [1,1,1,1,1],
    [1,1,1,1,1]
]; //don't forget your semi-colons

您希望将此二维数组展开为:

var myArray = [
    [1,1,1,1,1,0,0],
    [1,1,1,1,1,0,0],
    [1,1,1,1,1,0,0],
    [0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0],
];

这意味着您需要了解其中的区别。

从外部数组开始:

var myArray = [
    [...],
    [...],
    [...]
];

如果你想让这个数组更长,你需要检查它是否正确长度,并添加更多的内部数组来弥补差异:

var i,
    rows,
    myArray;
rows = 8;
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
    //check if the index exists in the outer array
    if (!(i in myArray)) {
        //if it doesn't exist, we need another array to fill
        myArray.push([]);
    }
}

下一步需要遍历每个数组中的每一列,我们将构建原始代码:

var i,
    j,
    row,
    rows,
    cols,
    myArray;
rows = 8;
cols = 7; //adding columns in this time
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
    //check if the index exists in the outer array (row)
    if (!(i in myArray)) {
        //if it doesn't exist, we need another array to fill
        myArray[i] = [];
    }
    row = myArray[i];
    for (j = 0; j < cols; j += 1) {
        //check if the index exists in the inner array (column)
        if (!(i in row)) {
            //if it doesn't exist, we need to fill it with `0`
            row[j] = 0;
        }
    }
}

答案 3 :(得分:3)

在您的情况下,您可以在不使用push的情况下执行此操作:

var myArray = [
    [1,1,1,1,1],
    [1,1,1,1,1],
    [1,1,1,1,1]
]

var newRows = 8;
var newCols = 7;

var item;

for (var i = 0; i < newRows; i++) {
    item = myArray[i] || (myArray[i] = []);

    for (var k = item.length; k < newCols; k++)
        item[k] = 0;    
}

答案 4 :(得分:2)

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;

var cols = 7;


for (var i = 0; i < rows; i++)

{

 for (var j = 0; j < cols; j++)

 {
    if(j <= c && i <= r) {
      myArray[i][j] = 1;
    } else {
      myArray[i][j] = 0;
    }
}

}

答案 5 :(得分:0)

你在数组元素(int)上调用push(),其中应该在数组上调用push(),这样处理/填充数组也没有意义 你可以这样做

for (var i = 0; i < rows - 1; i++)
{
  for (var j = c; j < cols; j++)
  {
    myArray[i].push(0);
  }
}


for (var i = r; i < rows - 1; i++)
{

  for (var j = 0; j < cols; j++)
  {
      col.push(0);
  }
}

你也可以使用if条件组合两个循环,如果行&lt; r,否则如果行&gt; = r

答案 6 :(得分:0)

创建am数组并放入第一个数组,在这种情况下,我从JSON响应中获取数据

$.getJSON('/Tool/GetAllActiviesStatus/',
   var dataFC = new Array();
   function (data) {
      for (var i = 0; i < data.Result.length; i++) {
          var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true);
          dataFC.push(serie);
       });

答案 7 :(得分:0)

下面的解决方案使用双循环将数据添加到案例3中的2x2数组的底部。内部循环将选定元素的值压入一个新的行数组中。然后,外循环将新的行数组推到现有数组的底部(请参见Newbie: Add values to two-dimensional array with for loops, Google Apps Script)。

在此示例中,我创建了一个从现有数组中提取节的函数。提取的部分可以是现有数组的一行(全部或部分),一列(全部或部分)或2x2部分。通过将相关部分从现有数组(arr)推入新数组来填充新的空白数组(newArr)。

 function arraySection(arr, r1, c1, rLength, cLength) {      
   rowMax = arr.length;
    if(isNaN(rowMax)){rowMax = 1};
   colMax = arr[0].length;
   if(isNaN(colMax)){colMax = 1};
   var r2 = r1 + rLength - 1;
   var c2 = c1 + cLength - 1;

   if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 || 
     r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax || 
   (c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
        throw new Error(
        'arraySection: invalid input')       
        return;
     };
   var newArr = [];

// Case 1: extracted section is a column array, 
//          all elements are in the same column
 if (c1 == c2){
   for (var i = r1; i <= r2; i++){ 
         // Logger.log("arr[i][c1] for i = " + i);
         // Logger.log(arr[i][c1]);
     newArr.push([arr[i][c1]]); 
     };
    };  

// Case 2: extracted section is a row array, 
//          all elements are in the same row
  if (r1 == r2 && c1 != c2){
    for (var j = c1; j <= c2; j++){ 
      newArr.push(arr[r1][j]); 
      };
   };  

// Case 3: extracted section is a 2x2 section 
    if (r1 != r2 && c1 != c2){     
     for (var i = r1; i <= r2; i++) {
          rowi = [];
       for (var j = c1; j <= c2; j++) {
          rowi.push(arr[i][j]);
        }
       newArr.push(rowi)
      };
    };
   return(newArr);
  };

答案 8 :(得分:0)

你也可以这样试试。

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;
var cols = 7;

for (var i = r; i < rows; i++)
{
    for (var j = c; j < cols; j++)
    {
        myArray.push([var[i],var[j])
    }
}

这将为您创建一个二维数组。