Checks how many arguments a function takes in Javascript?

后端 未结 3 1587
小鲜肉
小鲜肉 2020-12-01 10:12

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

But is there a way to determine how many arguments a function can take s

3条回答
  •  生来不讨喜
    2020-12-01 10:47

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

    function test( a, b, c ){}
    
    alert( test.length ); // 3
    

    By the way, this length property is quite useful, take a look at these slides of John Resig's tutorial on 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 .length property will give you the count of arguments that require to be set, not the count of arguments a function has.

提交回复
热议问题