Javascript 在Google脚本自定义函数中接受任意数量的参数?
我试图将COUNTIFS重新构建为一个googlescripts自定义函数,但有一件事遇到了麻烦:如何构建一个接受任意数量参数的函数 如果在google工作表中使用COUNTIFS,则输入如下所示:Javascript 在Google脚本自定义函数中接受任意数量的参数?,javascript,google-apps-script,google-sheets,google-docs,Javascript,Google Apps Script,Google Sheets,Google Docs,我试图将COUNTIFS重新构建为一个googlescripts自定义函数,但有一件事遇到了麻烦:如何构建一个接受任意数量参数的函数 如果在google工作表中使用COUNTIFS,则输入如下所示: =COUNTIFS(criteria_range1, criterion1, [criteria_range2, criterion2, ...]) 我的谷歌脚本可以是: function COUNTIFS(criteria_range1, criterion1){ // CountIFS
=COUNTIFS(criteria_range1, criterion1, [criteria_range2, criterion2, ...])
我的谷歌脚本可以是:
function COUNTIFS(criteria_range1, criterion1){
// CountIFS code
}
…但是如何获取函数中的可选参数?当传递给函数的参数数量可变时,可以引用。(示例支持AdamL的答案。)
自定义函数的自动完成特性在某种程度上滥用了jsdoc标记。通常用大括号括起来的“参数类型”,例如,{String}
,在函数帮助的“示例”部分中逐字使用,而参数名称在快速帮助中使用
您可以利用这一点来澄清具有任意参数的函数,如下所示
代码
/**
* 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];
...
/**
*计算沿路线行驶的距离。
*
*@param{“伦敦”、“曼彻斯特”、“利物浦”}
*路由逗号分隔的两个或多个映射的有序列表
*路线中包含的航路点。第一点
*是“起点”,最后是“终点”。
*
*@customfunction
*/
功能驾驶距离(路线){
如果(arguments.length<2)抛出新错误(“必须至少有2个航路点”)
变量来源=参数[0];
var destination=arguments[arguments.length-1];
...
当我在google docs中调用函数时,它仍然只显示所需的参数。下面是它们描述这种机制的地方:例如尝试函数numberOfArguments(){return arguments.length;}
并在具有不同数量参数的单元格中调用自定义函数。哦,如果您引用的是automcomplete信息,则没有一种简洁的方法来指定可选参数(但是您可以在@param描述中包含该信息)奇怪的是,如果我在脚本中输入相同的JSdoc代码,我会得到不同的结果,而不是“伦敦”、“曼彻斯特”等,我得到的是对象。