Get argument count (or even names) of javascript function object

前端 未结 2 832
北荒
北荒 2021-01-02 02:04

I want to evaluate callback function before accepting it. This means I need to know at least the count of accepted argumens - if count doesn\'t match, I\'ll leave warning in

相关标签:
2条回答
  • 2021-01-02 02:21

    A function has a length property which tells you how many named arguments it accepts. Note however, a function can use the arguments variable to access variables, even if it doesn't name them; length doesn't cater for this (nor is there an alternative which does).

    function foo(a, b) {
        for (var i=0;i<arguments.length;i++) {
            console.log(arguments[i]);
        }
    }
    
    console.log(foo.length); // reports 2, even though `foo` can access all your arguments!
    
    0 讨论(0)
  • 2021-01-02 02:36

    Here is shorter version var a = function(){ return [...arguments].length}

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