javascript 在 Apps 脚本中,如何在自定义函数中包含可选参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10843768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:13:46  来源:igfitidea点击:

In Apps Script, How to include optional arguments in custom functions

javascriptgoogle-apps-scriptgoogle-sheetscustom-function

提问by Jarod Meng

I want to write a custom function which has some mandatory arguments but can also accept a few optional arguments. I couldn't find any documentation on this. Does anyone know? Is it similar to Javascript?

我想编写一个自定义函数,它有一些强制参数,但也可以接受一些可选参数。我找不到任何关于此的文档。有人知道吗?它类似于Javascript吗?

回答by Eric Koleda

Custom functions don't have a concept of required and optional fields, but you can emulate that behavior using logic like this:

自定义函数没有必填字段和可选字段的概念,但您可以使用如下逻辑模拟该行为:

function foo(arg1, opt_arg2) {
  if (arg1 == null) {
    throw 'arg1 required';
  }
  return 'foo';
}

It's convention to use the prefix "opt_" for optional parameters, but it's not required.

使用前缀“opt_”作为可选参数是惯例,但这不是必需的。

回答by Magne

Yes, it is JavaScript (with a limited support for JsDoc too), so you can have an optional parameter with a default value:

是的,它是 JavaScript(对 JsDoc 的支持也有限),所以你可以有一个带有默认值的可选参数:

/**
 * This is myFunction.
 * @param {number} arg1 - Some number.
 * @param {string} arg2 - Some string.
 * @param {number} arg3 - [OPTIONAL] Additional numbers or ranges to add to value1.
 * @customFunction
**/
function myFunction(arg1, arg2, arg3=false) {
  return arg3;
}

And then you could call it in your spreadsheet using either:

然后您可以使用以下任一方法在电子表格中调用它:

=myFunction(1, "somestring", true)

Or without the optional parameter:

或者没有可选参数:

=myFunction(1, "somestring")

Since JavaScript dynamically handles the parameter list.

由于 JavaScript 动态处理参数列表。