简体   繁体   English

我可以将数组从 Google 电子表格传递给 Google App Script 方法吗?

[英]Can I pass an array into a Google App Script method from a Google Spreadsheet?

Can I pass an array into a Google App Script method from a Google Spreadsheet?我可以将数组从 Google 电子表格传递给 Google App Script 方法吗?

Suppose I have an App Script function that expects a list with two elements (note: this example is just an example so please do not tell me that my problem would be solved if I simply passed each element as a separate argument).假设我有一个 App Script 函数,它需要一个包含两个元素的列表(注意:这个例子只是一个例子,所以请不要告诉我如果我简单地将每个元素作为单独的参数传递,我的问题就可以解决)。 How do I call this function from a Google Spreadsheet cell?如何从 Google 电子表格单元格调用此函数?

I've tried both: '=myFunc([1,2])' and '=myFunc((1,2))' and both give me a Parse Error.我都试过: '=myFunc([1,2])' 和 '=myFunc((1,2))' 都给我一个解析错误。

In a spreadsheet formula, you can construct an embedded array using curly braces.在电子表格公式中,您可以使用花括号构造嵌入数组。 Semi-colons are row delimiters;分号是行分隔符; commas (or backslashes in locales that use a comma for the decimal separator) are column delimiters.逗号(或在使用逗号作为小数点分隔符的语言环境中的反斜杠)是列分隔符。

Now when such embedded arrays are passed to Google Apps Script, they are converted to a 2-dimensional Javascript array, just like referenced ranges are.现在,当此类嵌入数组传递给 Google Apps 脚本时,它们会被转换为二维 Javascript 数组,就像引用的范围一样。

So:所以:

=myFunc({1,2})

=myFunc({1;2})

function myFunc(value)
{
}

In the first formula, value will be [[1, 2]] .在第一个公式中, value将是[[1, 2]] In the second, it will be [[1], [2]] .在第二个中,它将是[[1], [2]]

One option is to pass a string of text and then transform it into an array inside the function myFunc:一种选择是传递一串文本,然后将其转换为函数 myFunc 中的数组:

function myFunc(value) {
  var arr = value.split(',');
}

=myFunc("1,2")

or要么

function myFunc(value) {
  /* remember you have to be careful with this function: eval() */
  var arr = eval(value);
}

=myFunc("[1,2]")

You can pass a selected range of cells into your Javascript function like so:您可以将选定范围的单元格传递到您的 Javascript 函数中,如下所示:

在此处输入图片说明

The Javascript function will be invoked, and the values will be passed to a singe parameter as the following:将调用 Javascript 函数,并将值传递给单个参数,如下所示:

[[""],[""],["E3"],[""],["E1"],[""],[""],[""]]

This array of arrays can be normalized, using a simple map and filter chaining:可以使用简单的mapfilter链接对这个数组数组进行归一化:

function calculateSalaryMultiple(values) {

  // values == [[""],[""],["E3"],[""],["E1"],[""],[""],[""]]
  values = values.map(x=>x[0]).filter(x=>x);

  // values == ["E3", "E1"]
  // Rest of your logic
  ...

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

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