【问题标题】:How to document a argument list with a variable length with known parameter types?如何用已知参数类型记录具有可变长度的参数列表?
【发布时间】:2011-09-22 13:03:03
【问题描述】:

相关:Correct way to document open-ended argument functions in 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 {...} 包含搜索词、替换及其选项的数组; index 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...

上面看起来很难看,但它应该让您了解我想要实现的目标:

  • 记录变量参数的类型(在本例中为数组)
  • 记录这个数组的值
  • 记录此数组中对象的属性

为了懒惰,我使用了数组而不是对象。欢迎提出其他建议。

【问题讨论】:

  • 我认为索引 0, 1, ... k 不是一个好方法。请改用字母或字母的序列。
  • @sergzach:数组由数字索引,而不是字母。我认为答案是我应该不那么懒惰。

标签: javascript jsdoc


【解决方案1】:

您的函数不是真正的可变参数,您应该将其签名更改为 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 标准,但它是Google 在他们的文档中使用什么

/**
 * 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;
}

【讨论】:

    【解决方案2】:

    除非您受到其他 API 的限制,否则我建议的第一件事是:不要将数组用于除您打算迭代的数据集合之外的任何内容。

    这里最好的方法可能是重构函数,使其接受三个参数或某种参数对象。例如:

    /**
     * @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 的限制),因为它会变得脆弱且最终会有些混乱。

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 1970-01-01
      • 2022-09-23
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多