0

Possible Duplicate:
Calling dynamic function with dynamic parameters in Javascript
javascript array parameter list

I'm looking for the Javascript equivalent of the following functionality I use in PHP:

function myfunc()
{
     $arg_arr = array();
     $arg_arr = func_get_args();

     $my_arg_val_1 = (!isset($arg_arr[1]) || ($arg_arr[1] == '')) ? true : $arg_arr[1];
}

Basically, I'm trying to get the function arguments. I want to write a javascript function to take one argument, but I want to add some code to do a few things with the second and third argument if it is provided, but I'm not sure how to pull this off.

Any assistance will be appreciated.

Thanks.

Community
  • 1
  • 1
ObiHill
  • 11,448
  • 20
  • 86
  • 135
  • You could just have one argument that's an array (I'm not a JS expert though, there might be a better way). – John V. Jan 19 '13 at 00:11

4 Answers4

2

Use the arguments variable.

It's not an array (it's an "Array-like object", which has a few differences with a standard array), but you can convert it to a real array this way :

function myfunc() {
    var argArray = Array.prototype.slice.call( arguments );
    /* ... do whatever you want */
}
Maël Nison
  • 7,055
  • 7
  • 46
  • 77
1

In JavaScript there is arguments variable available in each function. It looks like an array which contains all arguments passed to a function:

function myfunc() {
    var arg1 = arguments[0],
        arg2 = arguments[1],
        argc = arguments.length;
}

myfunc(1, "abc");  // arg1 = 1,
                   // arg2 = "abc",
                   // argc = 2
VisioN
  • 143,310
  • 32
  • 282
  • 281
0

This question is a dupe, but the answer is straightforward:

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    alert(arguments[i]);
  }
}
Peter Rowell
  • 17,605
  • 2
  • 49
  • 65
0

Those function you have been ported to js:

{php} .js

Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58