尝试使用推入二维数组时出错

Error when trying to use push into a 2d array

我试图将一个值压入二维数组,但出现错误:

Cannot read property 'push' of undefined

这是我的代码的 MWE:

var saida = new Array()
for (i in dbInfo){
  saida[i].push(i)
}

其中 dbInfo 是我的 sheet 中的一个范围,但对于此示例可以替换为任何其他范围。我需要输出是一个二维数组,这样我就可以将值计算到 sheet.

如果您刚刚创建了数组,则该数组为空。所以无论 n 的值是多少,saida[n] 都将是未定义的。

您需要先创建它。然后就可以推进去了

也许是这样的?不确定你需要什么。

var saida = new Array()
for (i in dbInfo){
  saida[i]=[]
  saida[i].push(i)
}

您需要将数组定义为 2d 例如:int[,] arr= new string[3, 2];

您将需要迭代两次。

for(int col1 = 0; col1 < arr.GetLength(0); col1++){
   for(int row1 = 0; row1 < arr.GetLength(1); row1++)
   { 
     arr[col1,row1] =  2; 
   }
 }

如果dbInfo是来自Sheet的Range类型的对象,那么使用getValues后返回的数组已经是一个二维数组,所以一个简单的赋值将够了:

function addData() {
  // your other code
  let dbInfoVals = dbInfo.getValues();
  let saida = dbInfoVals;
  console.log(saida)
}

但是,如果 dbInfo 是一维数组,可以使用 JavaScript 中的 splice 方法将其转换为二维数组:

function addData() {
  // your other code
  let saida = [];
  while (dbInfo.length){ 
    saida.push(dbInfo.splice(0, 2));
  }
  console.log(saida);
}

splice 的第二个参数将为您提供列数,因此您可能需要相应地调整它以匹配您的范围。

参考