如何记录具有已知参数类型的可变长度的参数列表
How to document a argument list with a variable length with known parameter types?
相关:在JSDoc 中记录开放参数函数的正确方法
我有一个函数,它通过访问arguments
变量来接受多个数组:
/**
* @param options An object containing options
* @param [options.bind] blablabla (optional)
*/
function modify_function (options) {
for (var i=1; i<arguments.length; i++) {
// ...
}
}
现在,我知道除了options
之外的每个参数都是一个数组,其中包含值得记录的值:
[search_term, replacement, options]
我不考虑将(冗长的)描述放在变量参数行中。
@param{…}一个包含搜索项、替换项及其选项的数组;索引0:函数中的搜索项;1:替换文本;2:可选选项(catch_errors:捕获错误并记录,escape:在替换文本中转义美元,pos:"L"用于将替换放在搜索词之前,"R"用于将其放在之后)不是可读的解决方案,并且类型不可见。
有没有一种方法可以记录变量参数的类型和值?
@param {...[]} An array with search terms, replacements and its options
@param {...[0]} The search term within the function
@param {...[1]} The replacement text
@param {...[2]} An optional object with obtions for the replacement
@param {...[2].catch_errors} catches errors and log it
@param {...[2].escape} etc...
上面看起来很难看,但它应该让你知道我试图实现的目标:
- 记录变量参数的类型(在本例中为数组)
- 记录此数组的值
- 记录此数组中对象的属性
由于懒惰,我使用了数组而不是对象。欢迎提出其他建议。
您的函数不是真正的可变参数,您应该将其签名更改为foundrama建议的签名。除了JSDoc的语法比foundrama建议的好一点之外
/**
* @param {String} searchTerm
* @param {String} replacementText
* @param {Object} opts (optional) An object containing the replacement options
* @param {Function} opts.catch_errors Description text
* @param {Event} opts.catch_errors.e The name of the first parameter
* passed to catch_errors
* @param {Type} opts.escape Description of options
*/
你会称之为
modify_text('search', 'replacement', {
catch_errors: function(e) {
},
escape: 'someEscape'
});
如果你真的有varargs风格的例子,它应该是一个可以在参数列表末尾传递的相同类型的变量,我像下面这样记录它,尽管它不是JSDoc标准,但它是谷歌在文档中使用的
/**
* Sums its parameters
* @param {...number} var_args Numbers to be added together
* @return number
*/
function sum(/* num, num, ... */) {
var sum = 0;
for (var i =0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
除非您受到其他API的限制,否则我建议的第一件事是:除了要迭代的数据集合之外,不要对任何内容使用数组
这里最好的方法可能是重新考虑函数,使其具有三个参数或某种param对象。例如:
/**
* @param {String} searchTerm
* @param {String} replacementText
* @param {Object} replacementOpts (optional) An object containing the replacement
* options; optional values in the object include:<ul>
<li>catch_errors {Type} description text...</li>
<li>escape {Type} description text...</li></ul>
*/
我强烈建议不要使用数组(再次:"除非你被某些API限制在你的控制范围之外),因为它会被证明是脆弱的,最终会有点令人困惑。
相关文章:
- PhpStorm警告:参数类型不可分配给参数类型
- 如何在JavaScript中为Google闭包编译器设置参数类型
- 方法作为参数类型
- Babel:ES6 中的函数参数类型
- 打字脚本:参数类型函数不能分配给参数类型函数
- 是否可以在 TypeScript 中使用构造函数作为另一个函数的参数类型
- 在带有句柄的迭代函数(每个)中传递参数类型对象
- 为什么可以在 JavaScript 中添加参数类型和返回类型
- JavaScript [参数:类型] 意思
- 检查函数调用是否具有正确的参数类型
- 使用groovy/grails获取参数类型
- “;“过载”;一个函数,或者在处理多个参数类型时具有两个单独的函数
- 参数类型的约束
- QtScript可以't调用参数类型为“”的函数;Q字符串&&”;
- JSHint表示“参数类型不匹配”;对于jQuery(这个)
- Angular2/TypeScript:错误TS2345:参数类型'String'不能赋值给's
- javascript中的Unity动态参数/参数类型
- 用Typescript编写的React应用中的错误参数类型
- 当类型声明为环境外部模块定义时,如何声明参数类型
- 在javascript中,我如何知道函数所期望的参数类型