如何记录具有已知参数类型的可变长度的参数列表

How to document a argument list with a variable length with known parameter types?

本文关键字:参数 类型 列表 何记录 记录      更新时间:2023-09-26

相关:在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限制在你的控制范围之外),因为它会被证明是脆弱的,最终会有点令人困惑。