views:

1113

answers:

4

Is it possible to send a variable number of arguments to a javascript function, from an array?

my arr = ['a','b','c']

var func = function()
{
    // debug 
    alert(arguments.length);
    //
    for(arg in arguments)
        alert(arg);
}

func('a','b','c','d'); // prints 4 which is what I want, then 'a','b','c','d'
func(arr); // prints 1, then 'Array'

I've recently written alot of python and it's a wonderful pattern to be able to accept varargs and send them. e.g.

def func(*args):
   print len(args)
   for i in args:
       print i

func('a','b','c','d'); // prints 4 which is what I want, then 'a','b','c','d'
func(*arr) // prints 4 which is what I want, then 'a','b','c','d'

is it possible in javascript to send an array to be treated as the arguments array?

+10  A: 

Use apply:

var arr = ['a','b','c'];

var func = function() {
  alert(arguments.length);

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

};

func.apply(null, arr);

Notice that null is used as the first argument of apply, that will set the this keyword to the Global object (window) inside func.

Also note that the arguments object is not really an Array, you can convert it by :

var argsArray = Array.prototype.slice.call(arguments);

And maybe is useful to you, that you can know how many arguments a function expects:

var test = function (one, two, three) {}; 
test.length == 3;

But anyway you can pass an arbitrary number of arguments...

CMS
apply or call? -
Jason S
@Jason: edited...
CMS
Thanks, apply does the trick, call in this case does not work. was that written in by mistake?
Fire Crow
@Fire: Yes, was a mistake!
CMS
+10  A: 

You can actually pass as many values as you want to any javascript function. The explicitly named parameters will get the first few values, but ALL parameters will be stored in the arguments array.

To pass the arguments array in "unpacked" form, you can use apply, like so (c.f. Functional Javascript):

var otherFunc = function() {
   alert(arguments.length); // Outputs: 10
}

var myFunc = function() {
  alert(arguments.length); // Outputs: 10
  otherFunc.apply(this, arguments);
}
myFunc(1,2,3,4,5,6,7,8,9,10);
danben
+1 great reference link
Fire Crow
+3  A: 

The apply function takes two arguments; the object this will be binded to, and the arguments, represented with an array.

some_func = function (a, b) { return b }
some_func.apply(obj, ["arguments", "are", "here"])
// "are"
August Lilleaas
+1  A: 

It's called splat operator. You can do it JavaScript using apply:

var arr = ['a','b','c','d'];
var func = function() {
    // debug 
    console.log(arguments.length);
}
func('a','b','c','d'); // prints 4 which is what I want, then 'a','b','c','d'
func(arr); // prints 1, then 'Array'
func.apply(null, arr);
Chandra Patni