Checks how many arguments a function takes in Javascript?

后端 未结 3 1377
小鲜肉
小鲜肉 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条回答
  • The arity property specifies the number of arguments the current function expected to receive. This is different to arguments.length which indicates how many actual arguments were passed in.

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

    Edit

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 10:54

    Edge cases

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

    
    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.length doesn't seem to recognize default values or rest operator.

    You can mess with this codePen

    0 讨论(0)
提交回复
热议问题