簡體   English   中英

如何在不使用“參數”的情況下計算JavaScript函數的參數數量?

[英]How to count the number of arguments to a JavaScript function without using “arguments”?

我一直在更新我前一段時間寫的一個庫,這樣做已經意識到在嚴格模式下進行測試時會出現意外錯誤。 這些是由於某些API函數開始時進行的檢查而導致的,如果參數數量不正確,則會引發錯誤。 這是一個例子:

if(arguments.length < 2){
    throw new Error("Function requires at least two arguments.");
}

第二個參數絕對可以是任何值,因此檢查null / undefined並不表示該參數是否丟失或無效。 但是,如果缺少該參數,則使用中絕對存在錯誤。 如果可能的話,我想將其報告為引發的Error

不幸的是,在嚴格模式下無法訪問arguments對象。 嘗試在上面的代碼片段中訪問它會產生錯誤。

如何在嚴格模式下執行類似的檢查,而無需訪問arguments對象?

編輯: Nina Scholz錯誤地將此問題標記為重復。

您可以檢查期望參數的長度( Function#length )並對照給定參數( arguments.length )進行檢查。

這也適用於'strict mode'

 'use strict'; function foo(a, b) { console.log('function length:', foo.length); console.log('argument length:', arguments.length); console.log('values:', a, b) } foo(); foo(1); foo(1, 2); foo(1, 2, 3); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM