获取函数参数长度,包括默认参数 [英] Get function parameter length including default params

查看:76
本文介绍了获取函数参数长度,包括默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用Function.length属性,则会获得函数期望的参数总数.

If you make use of the Function.length property, you get the total amount of arguments that function expects.

但是,根据文档(以及实际试用),该计数不包括默认参数.

However, according to the documentation (as well as actually trying it out), it does not include Default parameters in the count.

此数字不包括其余参数,并且仅包含第一个参数之前的参数,且具有默认值 -Function.length

This number excludes the rest parameter and only includes parameters before the first one with a default value - Function.length

我是否有可能(从函数外部)获得包括默认参数的计数?

Is it possible for me to somehow get a count (from outside the function) which includes Default parameters as well?

推荐答案

也许您可以自己解析它,例如:

Maybe you can parse it yourself, something like:

function getNumArguments(func) {
    var s = func.toString();
    var index1 = s.indexOf('(');
    var index2 = s.indexOf(')');
    return s.substr(index1 + 1, index2 - index1 - 1).split(',').length;
}

console.log(getNumArguments(function(param1, param3 = 'test', ...param2) {})); //3

这篇关于获取函数参数长度,包括默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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