Finding the number of function parameters in JavaScript

Possible duplicate:
Get function attribute

Say I have:

function a(x) {}; function b(x,y) {}; 

I want to write a function called numberOfParameters, which returns the number of parameters that the function usually takes. So that...

 numberOfParameters(a) // returns 1 numberOfParameters(b) // returns 2 
+4
source share
3 answers
 function f(x) { } function g(x, y) { } function param(f) { return f.length; } param(f); // 1 param(g); // 2 

Disclaimer:. This should only be used for debugging and automatic documentation. Based on the number of parameters that the function has in it, the definition in real code is a smell.

.length

+5
source

Just use length ?

 a.length // returns 1 b.length // returns 2 
+3
source

Like most languages, there is more than one way to do this (TMTOWTDI).

 function foo(a,b,c){ //... } 
  • Function object length method:

     foo.length(); // returns 3 
  • Disassemble it (using the test):

     args = foo.toString(); RegExp.lastIndex = -1; // reset the RegExp object /^function [a-zA-Z0-9]+\((.*?)\)/.test(args); // get the arguments args = (RegExp.$1).split(', '); // build array: = ["a","b","c"] 

    This gives you the option to use args.length and a list of actual argument names used in the function definition.

  • Disassemble it (using replacement):

     args = foo.toString(); args = args.split('\n').join(''); args = args.replace(/^function [a-zA-Z0-9]+\((.*?)\).*/,'$1') .split(', '); 

Note: This is a basic example. The regular expression should be improved if you want to use it for wider use. Above, function names should only be letters and numbers (not internationalized), and arguments cannot contain any parentheses.

0
source

All Articles