4

Possible Duplicate:
Get a function's arity

Say I have:

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

I want to write a function called numberOfParameters that returns the number of parameters that a function normally accepts. So...

numberOfParameters(a) // returns 1
numberOfParameters(b) // returns 2
Community
  • 1
  • 1
Steve
  • 69
  • 5

3 Answers3

5
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 auto documentation. Relying on the number of parameters that a function has in it's definition in actual code is a smell.

.length

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • Perfect, thanks! Why is it a bad idea to use Function.length in actual code? – Steve Jun 09 '11 at 13:44
  • @Steve Why do you care how many parameters a function takes? I can't think of any solid non-hackish use cases for caring about the parameters. Using `arguments` inside a function is fine however. – Raynos Jun 09 '11 at 14:00
3

Just use length?

a.length // returns 1
b.length // returns 2
Niklas
  • 29,752
  • 5
  • 50
  • 71
1

Like most languages, there's more than one way to do it (TMTOWTDI).

function foo(a,b,c){
   //...
}
  1. Length method of Function object:

    foo.length();                                  // returns 3
    
  2. Parse it (using 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 ability to use args.length, and list the actual argument names used in the function definition.

  3. Parse it (using replace):

    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 regex should be improved if you wish to use this for broader use. Above, function names must be only letters and numbers (not internationalized) and arguments can't contain any parentheses.

vol7ron
  • 40,809
  • 21
  • 119
  • 172