问题
Can I pass an array into a Google App Script method from a Google Spreadsheet?
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). How do I call this function from a Google Spreadsheet cell?
I've tried both: '=myFunc([1,2])' and '=myFunc((1,2))' and both give me a Parse Error.
回答1:
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.
So:
=myFunc({1,2})
=myFunc({1;2})
function myFunc(value)
{
}
In the first formula, value
will be [[1, 2]]
. In the second, it will be [[1], [2]]
.
回答2:
One option is to pass a string of text and then transform it into an array inside the function 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]")
来源:https://stackoverflow.com/questions/18296634/can-i-pass-an-array-into-a-google-app-script-method-from-a-google-spreadsheet