【问题标题】:Accept Arbitrary Number of Arguments in Google Scripts Custom Function?接受 Google Scripts 自定义函数中的任意数量的参数?
【发布时间】:2014-10-29 22:31:50
【问题描述】:

我正在尝试将 COUNTIFS 重新构建为 Google 脚本自定义函数,但遇到一件事:如何构建一个接受任意数量参数的函数?

如果您在 google 表格中使用 COUNTIFS,则输入如下所示:

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

我的 Google 脚本可以是这样的:

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

...但是如何在我的函数中获取可选参数?

【问题讨论】:

    标签: javascript google-apps-script google-sheets google-docs


    【解决方案1】:

    当传递给函数的参数数量可变时,您可以引用arguments object

    【讨论】:

    • 当我在谷歌文档中调用函数时,它仍然只显示所需的参数。这是他们描述这种机制的地方:developers.google.com/apps-script/guides/sheets/…
    • 尝试例如function numberOfArguments() {return arguments.length;}并在具有不同数量参数的单元格中调用自定义函数。
    • 哦,如果您指的是自动完成信息,则没有一种指定可选参数的简洁方法(但是您可以在@param 描述中包含该信息)。
    【解决方案2】:

    (支持 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];
      ...
    

    【讨论】:

    • 奇怪的是,如果我将相同的 JSdoc 代码放入脚本中,我会得到不同的结果——而不是“伦敦”、“曼彻斯特”等,我得到的是 Object。
    猜你喜欢
    • 2011-04-04
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2018-11-04
    • 2015-08-14
    • 1970-01-01
    相关资源
    最近更新 更多