我一直在努力解决这段代码问题。我正在尝试遍历一个数组(从Google Spreadsheet数据创建)并有条件地将整行数据(基于该行中一个单元格的内容)复制到具有相同列数的新行数组中。然后,我计划将此数组写入电子表格中的匹配范围。
数据数组似乎与[k]
作为行索引,[u]
作为列索引正常工作。
目前我在运行时看到此错误:TypeError:无法从undefined @此代码行读取属性“0”:targetArray [m] [u] .push(data [k] [u]);
当我逐步执行这行代码:targetArray [m] [u] .push(data [k] [u])时,值为m = 0,u = 0,k = 2,i = 5。那么,为什么数据[5] [0]中的数组元素不能写入targetArray [0] [0]?如果那个特定的单元格是空的,那么它仍然应该被复制到数组中,对吗?我不确定“未定义”的来源。目标数组从初始化设置为[]。样本数据数组元素是:[“”,“”,“显示”,“”,1,“A”,“”,“”,“”] - > 1行9列。
任何指针?
var sheetArray = ss.getSheets(); //returns an array of all the sheets
var numSheets = sheetArray.length;
var targetArray = [];
var m = 0; //target array counter
for (j = 6; j < numSheets; j++) {
var data = sheetArray[j].getDataRange().getValues(); //getdatarange -> return the range of the data for the active sheet // getvalues -> returns 2D array of values for the given range
var numRows = data.length; //returns the number of rows in the data array
var numColumns = data[1].length; //returns the number of columns in the 2nd row of the data array
for (var i = 0; i < numColumns; i++) { //loop through all columns of active sheet
if (data[1][i] == "Build Prio [Alpha(A), Beta(B)]") { //check data heading value in each column of Row 2, when column heading matches run next for loop
for (var k = 0; k < numRows; k++) { //k = row index & i = column index
if (data[k][i] == 'A') { // check if cell contents are equal to A
for (var u = 0; u < numColumns; u++) { //loop through all columns in the current row
targetArray[m][u].push(data[k][u]); //set the value of each column in the current row to the new array
}
m++; //advances the targetArray row index
}
}
}
}
}
答案 0 :(得分:0)
在代码中添加了一些注释。不要在数组中执行m ++和push():)
var sheetArray = ss.getSheets(); //returns an array of all the sheets
var numSheets = sheetArray.length;
var targetArray = [];
var m = 0; //target array counter
for (j = 6; j < numSheets; j++) {
var data = sheetArray[j].getDataRange().getValues(); //getdatarange -> return the range of the data for the active sheet // getvalues -> returns 2D array of values for the given range
var numRows = data.length; //returns the number of rows in the data array
var numColumns = data[1].length; //returns the number of columns in the 2nd row of the data array
for (var i = 0; i < numColumns; i++) { //loop through all columns of active sheet
if (data[1][i] == "Build Prio [Alpha(A), Beta(B)]") { //check data heading value in each column of Row 2, when column heading matches run next for loop
for (var k = 0; k < numRows; k++) { //k = row index & i = column index
if (data[k][i] == 'A') { // check if cell contents are equal to A
//just push the whole row at once:
targetArray.push(data[k]); //push the whole row in targetarray
}
//no need for m++ since push adds a row.
}
}
}
}
}