检查一个函数在 Javascript 中接受多少个参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4138012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:28:23  来源:igfitidea点击:

Checks how many arguments a function takes in Javascript?

javascript

提问by ajsie

With arguments.lengthI can see how many arguments were passed into a function.

随着arguments.length我可以看到有多少参数传递给函数。

But is there a way to determine how many arguments a function can take so I know how many I should pass in?

但是有没有办法确定一个函数可以接受多少个参数,这样我就知道应该传入多少个参数?

回答by Harmen

Function.lengthwill do the job (really weird, in my opinion)

Function.length会做这项工作(在我看来真的很奇怪)

function test( a, b, c ){}

alert( test.length ); // 3

By the way, this length property is quite useful, take a look at these slidesof John Resig's tutorial on Javascript

顺便说一句,这个长度属性非常有用,请看一下John Resig 的 Javascript 教程的这些幻灯片

EDIT

编辑

This method will only work if you have no default value set for the arguments.

此方法仅在您没有为参数设置默认值时才有效。

function foo(a, b, c){};
console.log(foo.length); // 3


function bar(a = '', b = 0, c = false){};
console.log(bar.length); // 0

The .lengthproperty will give you the count of arguments that require to be set, not the count of arguments a function has.

.length属性将为您提供需要设置的参数计数,而不是函数具有的参数计数。

回答by Matthew Vines

The arityproperty specifies the number of arguments the current function expected to receive. This is different to arguments.lengthwhich indicates how many actual arguments were passed in.

arity属性指定当前函数预期接收的参数数量。这与arguments.lengthwhich 表示传入了多少实际参数不同。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/arity

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/arity

Edit

编辑

Note that arityhas been deprecated since v1.4. The correct way to get the number of arguments expected is now function.lengthas suggested by Harmen.

请注意,arity自 v1.4 以来已被弃用。获得预期参数数量的正确方法现在function.length是 Harmen 所建议的。

回答by 538ROMEO

Edge cases

边缘情况

Beware, before counting on fn.length, there are some edge cases where the result may not be what you expect:

请注意,在指望 之前fn.length,有一些边缘情况可能会导致结果与您预期的不同:


const fn1 = ( a, b ) => {}; //       length: 2
const fn2 = ( a = 0, b ) => {}; //   length: 0
const fn3 = ( ...params ) => {};//   length: 0
const fn4 = ( a, b = 1, c ) => {};// length: 1

fn.lengthdoesn't seem to recognize default values or rest operator.

fn.length似乎无法识别默认值或休息运算符。

You can mess with this codePen

你可以弄乱这个codePen