I'd like to accept a variable number of individual cells as arguments into a custom Google Sheets function, eg:
function least(range){
var res = 100000;
for (var i = 0; i < range.length; i++){
if (range[i] < res) res = range[i];
}
return res;
}
(I'm aware that returning the minimum value of a list is already built-in; this is an example.)
I'd like to run the function on a sheet with disjoint cells, like so:
=least(A1, A3, A5, B2)
where I am able to use an arbitrary number of arguments.
I have tried using what appears to be JavaScript's variadic argument object , like this:
function least(...range){
// access elements using range as an array
}
but in this case, I get an error: "Missing formal parameter."
Am I not using the variadic argument correctly, or is it disallowed in Google Scripts, or do they have a house style for this that's different from JavaScript's?
Thanks in advance.
It appears that the object arguments
contains any/all variadic function input. I load that object's values into an array at the top of the function like so, and have no trouble from the Google Sheets compiler (and it works on the sheet):
function least(){
var range = arguments;
// range now contains all of the arguments supplied to the function
}
I've created this restParam function to solve this issue. I know the question as been ask a long time ago but maybe it can help others
Here's the func:
function restParam(maxParam, args, containerArray) {
Logger.log("Args length");
Logger.log(args.length);
if(args.length > maxParam) {
for(var i = maxParam -1; i < args.length; i++) {
Logger.log(args[i])
containerArray.push(args[i]);
};
return containerArray;
};
};
and heres an example:
//function as 14 params
function foo(address, offset, sale, siring, sorting, breedable, stage, class, pureness, region, title, mystic, num_mystic, parts) {
var restAr = [];;
restParam(14, arguments, restAr);
...}
The example you gave is not using the variadic argument object. It's using the rest parameter ([ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters][1] )
You can use it like a normal array:
function least(...range) {
var res = Infinity;
for (var i = 0; i < range.length; i++){
if (range[i] < res) res = range[i];
}
return res;
}
and use it like this
least(1, 2, 3) // -> 1 !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.