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?
Update: Since ES6, you can simply use the spread syntax when calling the function:
Since ES6 also if you expect to treat your arguments as an array, you can also use the spread syntax in the parameter list, for example:
And you can combine it with normal parameters, for example if you want to receive the first two arguments separately and the rest as an array:
And maybe is useful to you, that you can know how many arguments a function expects:
But anyway you can pass an arbitrary number of arguments…
The spread syntax is shorter and “sweeter” than
applyand if you don’t need to set thethisvalue in the function call, this is the way to go.Here is an apply example, which was the former way to do it:
Nowadays I only recommend using
applyonly if you need to pass an arbitrary number of arguments from an array and set thethisvalue.applytakes is thethisvalue as the first arguments, which will be used on the function invocation, if we usenullin non-strict code, thethiskeyword will refer to the Global object (window) insidefunc, in strict mode, when explicitly using ‘use strict’ or in ES modules,nullwill be used.Also note that the
argumentsobject is not really an Array, you can convert it by:And in ES6:
But you rarely use the
argumentsobject directly nowadays thanks to the spread syntax.