繁体   English   中英

在 Google Apps 脚本中将数组输入到 Math.Max

[英]Inputting an array into Math.Max in Google Apps Scripts

在 Google 表格中,我有一个基于我在网上找到的一些帖子/博客的自定义表单,以了解有关 Google App Scripts 的更多信息。 该表单可以正常工作,但我在应该为该行创建 ID 的列上遇到问题。

从我的阅读来看,我的问题似乎是 math.max() 需要一个列表而不是一个数组。 此外,我为常规 Javascript 找到的所有方法似乎都不适用于 Google Apps 脚本。 例如,math.max.apply(null,array)。

我必须迭代数组还是有什么东西可以让 max() 获取一个数组?

这是我一直在玩的代码。

function itemAdd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var sh = SpreadsheetApp.getActiveSheet();
  var lRow = sh.getLastRow();
  var range = sh.getRange(3,1,lRow,1);
  var maxNum = Math.max(range)
  sheet.appendRow([maxNum,form.category, form.item, form.manupub, 
form.details, form.quantity]);
  return true;
}

您可以在 GAS 中使用Math.max.apply() getValues() 检索到的数据是一个二维数组。 因此,为了使用Math.max.apply()的数据,必须将数组展平。 通过反映这一点,可以对示例脚本进行如下修改。

脚本:

function itemAdd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var sh = SpreadsheetApp.getActiveSheet();
  var lRow = sh.getLastRow();
  var range = sh.getRange(3,1,lRow,1);
  var ar = Array.prototype.concat.apply([], range.getValues());
  var maxNum = Math.max.apply(null, ar);
  sheet.appendRow([maxNum,form.category, form.item, form.manupub, form.details, form.quantity]);
  return true;
}

如果我误解了你的问题,我很抱歉。

以下应该有所帮助。 您需要从范围中提取值。 这将返回一个二维数组。

var vals = range.getValues();
//assuming your values are non negative, set the initial max to 0
var max = 0;
for(var i=0; i<vals.length; i++) {
  max = Math.max(max, vals[i][0]);
}
//max will now have the largest value

.flat()和扩展运算符...的简洁替代方案:

var vals = range.getValues().flat();
var max = Math.max(...vals)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM