Google Apps Scripts setValues()不正确的高度错误

时间:2016-08-07 17:26:31

标签: javascript google-apps-script google-sheets

我已经看过其他类似的问题了,但是我以一种独特的方式得到了我的阵列,我无法弄清楚如何将其改为二维阵列。

  //Special function for adding arrays, just use sumArray on first array with second array in parenthesis
  //==========================================
  Array.prototype.sumArray = function (arr) {
    
    var sum = this.map(function (num, idx) {
      return num + arr[idx];
    });
    
    return sum;
  }
  var array1 = [1,2,3,4];
  var array2 = [5,6,7,8];
  var sum = array1.sumArray(array2);
  Logger.log("sum: " + sum);
  //==========================================

  var calc = ss.getRangeByName( "calc" );
  var target = ss.getRangeByName( "target" );
  var current = ss.getRangeByName( "current" );
  var left = ss.getRangeByName( "left" );
  
  var gainedEVs = calc.getValues();
  var goalEVs = target.getValues();
  var oldEVs = current.getValues();
  var leftEVs = left.getValues();
  
  //Make everything ints
  //==========================================
  for(var i = 0; i < oldEVs.length; i++) {
    Logger.log(oldEVs.length);
    oldEVs[i] = parseInt(oldEVs[i]);
  }
  for(var i = 0; i < gainedEVs.length; i++) {
    
    gainedEVs[i] = parseInt(gainedEVs[i]);
  }
  for(var i = 0; i < goalEVs.length; i++) {
    
    goalEVs[i] = parseInt(goalEVs[i]);
  }
  for(var i = 0; i < leftEVs.length; i++) {
    
    leftEVs[i] = parseInt(leftEVs[i]);
  }
  //==========================================
  
  var newEVs = [[oldEVs.sumArray(gainedEVs)]];
  var newLeft = [[goalEVs.subArray(newEVs)]];

  //Now I try to set values and I get the error
  current.setValues(newEVs);

我尝试将setValues更改为setValues([newEVs]);但这也不起作用。关于如何让我的newEV数组达到正确高度的任何线索?它具有正确数量的值,但这些值存储在列中,而不是行中。 (在这种情况下,我的所有范围都是6行1列)

1 个答案:

答案 0 :(得分:2)

由于范围很小,因此您不必过于担心性能,因此可以使用循环将它们从行转换为列:

var column = [];
for (var i=0; i<newEVs.length; i++){
  column.push([newEVs[i]]);
}
current.setValues(column);