Get the length of a function parameter, including default parameters

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

However, according to the documentation (as well as its attempts), it does not include the default parameters in the counter.

This number excludes the stop parameter and includes only parameters up to the first with the default value - Function.length

Is it possible for me to somehow get a counter (outside the function) that also includes default parameters?

+4
source share
1 answer

Perhaps 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
Run codeHide result
+2

Source: https://habr.com/ru/post/1672706/


All Articles