在 Google Apps 脚本中,我将数字行拉入数组中
我需要找到该数组中每个元素的总和
这段代码工作正常:(这将值拉入数组)
var test = [];
test = sheet.getRange(13, 6, 4, 24).getValues();
我尝试了几种不同的公式,但未能使其正常工作:
function testSum (test) {
let total = 0;
for (const i of test) {
total += i;
}
return total;
}
var test1 = test.flat();
var test1 = test.reduce((a, b) => a + b, 0);
尝试了我能找到的一切,但没有任何效果
const test = [
[
583.95,
'',
'',
'',
'',
'',
225,
'',
11,
'',
20,
'',
21.95,
'',
279,
'',
19,
'',
8,
'',
690,
'',
'',
'',
],
[
145,
'',
80,
'',
10,
'',
'',
'',
'',
'',
'',
'',
55,
'',
'',
'',
'',
'',
'',
'',
110,
'',
'',
'',
],
['', '', '', '', ''],
];
const columnWiseSums = [];
for (const ele of test) {
let sum = 0;
columnWiseSums.push(ele.reduce((prev, curr) => typeof curr === 'number' ? prev + curr : prev, 0));
}
console.log(columnWiseSums);
还有其他求和的方法,但我用了
array.reduce
一个