Is it possible to send a variable number of arguments to a JavaScript function?

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

var 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 a lot 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?

12 Answers
12

Leave a Comment