Accept Arbitrary Number of Arguments in Google Scripts Custom Function?

回眸只為那壹抹淺笑 提交于 2019-12-06 01:52:11

问题


I'm trying to re-build COUNTIFS as a Google Scripts Custom Function and having trouble with one thing: how do I build a function that accepts an arbitrary number of arguments?

If you use COUNTIFS in google sheets, the inputs look like this:

=COUNTIFS(criteria_range1, criterion1, [criteria_range2, criterion2, ...])

My Google Script can be this:

function COUNTIFS(criteria_range1, criterion1){
    // CountIFS code
}

...but how do I get the optional arguments in my function?


回答1:


You can reference the arguments object when the number of arguments passed to a function is variable.




回答2:


(Example to support AdamL's answer.)

The autocomplete feature for custom functions abuses jsdoc tags somewhat. The "parameter type" which is normally enclosed in braces, e.g. {String}, is used verbatim in the "Example" section of the function's help, while the parameter name is used in the quick-help.

You can take advantage of this to clarify functions with arbitrary parameters, as shown here.

Code

/**
 * Calculate the driving distance along a route.
 *
 * @param {"london","manchester","liverpool"}
 *                   route  Comma separated ordered list of two or more map
 *                          waypoints to include in route. First point
 *                          is 'origin', last is 'destination'.
 *
 * @customfunction
 */
function drivingDistance(route) {
  if (arguments.length < 2) throw new Error( "Must have at least 2 waypoints." )
  var origin = arguments[0];
  var destination = arguments[arguments.length-1];
  ...


来源:https://stackoverflow.com/questions/26641791/accept-arbitrary-number-of-arguments-in-google-scripts-custom-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!