计算 Javascript 中的参数

Til*_*ddy 3 javascript function ecmascript-6

Mozilla 的文档说的是:

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

  console.log((function(a, b = 1, c) {}).length);
  // 1, only parameters before the first one with 
  // a default value is counted
Run Code Online (Sandbox Code Playgroud)

那么在这种情况下我如何能够计算参数呢?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length

jfr*_*d00 7

这里发生了两个不同的事情,即定义的参数实际传递的参数

对于已定义的函数,您可以使用以下命令访问函数定义中定义的参数数量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
Run Code Online (Sandbox Code Playgroud)

另外,在函数内部,您可以使用 来查看对于该函数的给定调用实际传递了多少个参数arguments.length。假设您有一个函数被编写为接受可选回调作为最后一个参数:

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");
});                                 
Run Code Online (Sandbox Code Playgroud)