我一直在努力處理這段代碼一段時間。我試圖循環訪問一個數組(從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。那麼,爲什麼data [5] [0]中的數組元素不能寫入targetArray [0] [0]?如果這個特定的單元格是空的,那麼它仍然應該被複制到數組中,對吧?我不確定「未定義」是從哪裏來的。目標數組從初始化設置爲[]。示例數據數組元素是:[「」,「」,「Display」,「」,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
}
}
}
}
}
您可以使用調試器遍歷每行代碼並觀察代碼中每個變量的內容。 [Google文檔 - 調試器和斷點](https://developers.google.com/apps-script/troubleshooting#using_the_debugger_and_breakpoints)如果你這樣做了,你可能會發現一些東西。 –
你的問題並不清楚 - 事實上,毫無疑問。哪裏不對?你希望看到什麼_,你看到了什麼_?我們可以指出一些可能的優化,但如果沒有明確說明您的代碼如何達不到您的期望,那麼就沒有問題要解決。 – Mogsdad