如何在不使用 "arguments" 的情况下计算 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) and check against the given arguments (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; }