猿问

如何使用 Google App Script 用分隔符拆分数组的总和?

我从谷歌表的单列中得到了一个数组,比如[[23],[25],[26],[89],[""],[45],[78],[62],[""],[123],[45],[68]]我如何用空值拆分它[]并获得每个子数组的总和,比如 ( 163/185/236) 或更多,因为数组长度可能超过 1000,包括 20-50 个空值?


我从答案修改了脚本。但它在我的情况下不起作用。我不明白为什么?


function getSums(){

    var ss = SpreadsheetApp.getActiveSpreadsheet();

    var sh = ss.getSheetByName('TemplateTest');

    var r = sh.getRange(1, 1, sh.getLastRow());

    var arr = r.getValues(); //log: [[23],[25],[26],[89],[""],[45],[78],[62],[""],[123],[45],[68]]

    var sums = [];

    var sum = 0;

    // iterate through the array

    for (var i = 0; i < arr.length; i ++) {

         if (arr[i].length == 0 || i == arr.length - 1) {

             // empty array, push sum to array and reset

             sums.push(sum);

             sum = 0;

         } else {

        // array has values, sum them up and add to sum

             sum += arr[i].reduce((a, b) => a + b);

         }

    }

    Logger.log(sums) //log: [16345786212345]

}

我哪里错了,我该如何解决?



当年话下
浏览 117回答 2
2回答

大话西游666

您可以采用单循环并添加值,直到达到undefined值,然后将总和推送到结果集并重置sum。最后,也将最终总和推入结果集。var data = [[23.0], [25.0], [26.0], [89.0], [""], [45.0], [78.0], [62.0], [""], [123.0], [45.0], [68.0]],&nbsp; &nbsp; result = [],&nbsp; &nbsp; sum = 0,&nbsp; &nbsp; value,&nbsp; &nbsp; i;for (i = 0; i < data.length; i++) {&nbsp; &nbsp; value = data[i][0];&nbsp; &nbsp; if (value === "") {&nbsp; &nbsp; &nbsp; &nbsp; result.push(sum);&nbsp; &nbsp; &nbsp; &nbsp; sum = 0;&nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; sum += value;}result.push(sum);console.log(result);

波斯汪

使用array.reduce,它可以很容易地完成。const data = [&nbsp; [23.0],&nbsp; [25.0],&nbsp; [26.0],&nbsp; [89.0],&nbsp; [],&nbsp; [45.0],&nbsp; [78.0],&nbsp; [62.0],&nbsp; [],&nbsp; [123.0],&nbsp; [45.0],&nbsp; [68.0]];let [result, sum] = data.reduce(&nbsp; ([arr, sum], curr) => {&nbsp; &nbsp; if (curr.length) sum += curr[0];&nbsp; &nbsp; else arr.push(sum);&nbsp; &nbsp; return [arr, sum];&nbsp; },&nbsp; [[], 0]);result.push(sum); //push last dataconsole.log(result);console.log(result.join("."));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答