用JavaScript计数参数 [英] Counting parameters in Javascript

查看:84
本文介绍了用JavaScript计数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mozilla的文档怎么说:

What the docs at Mozilla says:

  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

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

So how will I ever be able to count parameters in such cases ?

https://developer.mozilla .org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/length

推荐答案

这里发生了两件事,分别定义了参数实际通过的参数.

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

对于已定义的函数,您可以使用fn.length访问该函数的定义中定义的参数数量:

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

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

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");
});                                 

这篇关于用JavaScript计数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆