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.

1
  • You could just have one argument that's an array (I'm not a JS expert though, there might be a better way). Commented Jan 19, 2013 at 0:11

4 Answers 4

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 */
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks. The simpler the better I suppose.
0

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

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    alert(arguments[i]);
  }
}

Comments

0

Those function you have been ported to js:

{php} .js

3 Comments

But should probably not be used except for looking how to use the underlying JS features.
@Nabil Thanks, I use PHPJS quite extensively but in this case, it seems a bit overkill for the circumstance.
@Chuck Ugwuh, array()... yes, but not the other functions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.