Checks how many arguments a function takes in Javascript?

后端 未结 3 1585
小鲜肉
小鲜肉 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: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

提交回复
热议问题