Counting parameters in Javascript

前端 未结 2 439
感情败类
感情败类 2021-01-16 07:53

What the docs at Mozilla says:

  console.log((function(...args) {}).length); 
  // 0, rest parameter is not counted

  console.log((function(a, b = 1, c) {})         


        
相关标签:
2条回答
  • 2021-01-16 08:37

    There are two separate things going on here with parameters defined and arguments actually passed.

    For a defined function, you can get access to the number of parameters that are defined in the definition of the function with fn.length:

    function talk(greeting, delay) {
        // some code here
    }
    
    console.log(talk.length);     // shows 2 because there are two defined parameters in 
                                  // the function definition
    

    Separately, from within a function, you can see how many arguments are actually passed to a function for a given invocation of that function using arguments.length. Suppose you had a function that was written to accept an optional callback as the last argument:

    function talk(greeting, delay, callback) {
        console.log(arguments.length);     // shows how many arguments were actually passed
    }
    
    talk("hello", 200);    // will cause the function to show 2 arguments are passed
    talk("hello", 200, function() {    // will show 3 arguments are passed
         console.log("talk is done now");
    });                                 
    
    0 讨论(0)
  • 2021-01-16 08:52

    Not sure if this answers what you were asking... based on your examples though...

    var x = function (...args) {
      //console.log(Object.keys(args).length);
      //console.log(Object.keys(arguments).length);
      console.log(arguments.length);
    }
    

    https://jsfiddle.net/hxm4smc1/555/

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