2011-06-25 30 views
7

相關: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 {...}一個包含搜索項,替換項及其選項的數組;索引0:函數內的搜索項; 1:替換文字; 2:可選選項(catch_errors:捕獲錯誤並記錄它,在替換文本中escape: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... 

以上相貌醜陋,但它應該給你什麼,我試圖實現一個想法:

  • 文檔的變量參數(數組在這種情況下)類型
  • 文檔此數組
  • 文檔的對象的該數組

對於懶惰內的屬性,我已經採用的值d數組而不是對象。其他建議總是受歡迎的。

+0

使用我認爲索引* 0,1, ... k *不是一個好方法。用字母或字母代替。 – sergzach

+0

@sergzach:數組以數字索引,而不是字母。我想答案是我應該不那麼懶惰。 – Lekensteyn

回答

5

你的函數並不是真正的可變參數,你應該將它的簽名更改爲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' 

}); 

如果你確實有一個可變參數風格的情況下,它應該是一個變量可在參數列表的末尾傳遞同一類型,我記錄它像下面,但它不是一個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; 
} 
+0

看起來很明智,謝謝! – Lekensteyn

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的控制之外界)使用數組。因爲這將被證明既脆,最終有點混亂