3 回答

TA貢獻1797條經驗 獲得超6個贊
一種更有效的計算總和的方法是使用reduce,這樣你就可以擺脫for
循環。
可以僅使用函數計算總和reduce
。所有其他函數:flat
,?map
,filter
用于確保數據正確,因為我們不知道您的電子表格文件是如何構建的以及您使用的值是什么。有關每個步驟的詳細說明,請參閱代碼注釋。
解決方案:
const netSquare = sheet_origin2.getRange('L2:L').getValues(). // get column L (12th column)
? ? ? ? ? ? ? ? ? ? flat(). // convert the 2D array to 1D array
? ? ? ? ? ? ? ? ? ? filter(v=>v!=''). // filter out empty cells
? ? ? ? ? ? ? ? ? ? map(v=>parseInt(v)); // convert string numbers to integers
const sum = netSquare.reduce((a,b)=>a+b); // add all numbers together
sheet_destination.getRange(sheet_destination.getLastRow(), 2, 1, 1).setValue(sum);

TA貢獻1757條經驗 獲得超7個贊
最后一行≠行數,尤其是因為您跳過了第一行。
.getValues()
返回一個二維數組,所以你需要使用netSquare[i][0]
您應該在 for 循環中使用要迭代的數組的長度,并確保您的索引不會越界。
function sum() {
? // ... define the sheets ...
? var lastRow = sheet_origin2.getLastRow();
? var numRows = lastRow - 1; // Subtract one since you're skipping the first row
? var netSquare = sheet_origin2.getRange(2, 12, numRows, 1).getValues();
? var sum = 0;
? for (var i=0; i<netSquare.length; i++) {
? ? sum += netSquare[i][0];
? }
? sheet_destination.getRange(sheet_destination.getLastRow(), 2, 1, 1).setValue(sum);
}

TA貢獻1812條經驗 獲得超5個贊
最短的修復方法是類型轉換,因為當您獲取數據時它們變成了字符串。
改變你的:
?sum?+=?netSquare[i];
到:
?sum?+=?parseInt(netSquare[i]);?//?if?whole?number ?sum?+=?parseFloat(netSquare[i]);?//?if?number?has?decimal
這強制該netSquare[i]
值的類型為整數/浮點數,可以作為數字添加。當我們確定 netSquare[i] 值都是數字時,就不會有問題。
對于可能出現的問題,您可以在類型轉換非數字數據時檢查可能的結果。
添加回答
舉報