Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass unknown number of parameters to JS function [duplicate]

A pattern in some javascript libraries is to be able to pass any number of parameters to a function:

functiona(param1)
functiona(param1, param2, param3)
functiona(param1, param2)

I have an array of unknown length, and I'd like to pass all the array items as parameters to a function like functiona(). Is this possible? If so, what is the syntax for doing this?

like image 612
Alex Avatar asked Sep 02 '25 13:09

Alex


2 Answers

What you want is probably Function.prototype.apply().

Usage:

var params = [param1, param2, param3];
functiona.apply(this, params);

As others noted, functiona declaration may use arguments, e.g.:

function functiona()
{
    var param1 = this.arguments[0];
    var param2 = this.arguments[1];
}

But it can use any number of normal parameters as well:

function foo(x, y)
{
    console.log(x);
}
foo.apply(this, [10, 0, null]); // outputs 10
like image 82
zlumer Avatar answered Sep 05 '25 05:09

zlumer


Use arguments:

The arguments object is an Array-like object corresponding to the arguments passed to a function.

like image 39
CD.. Avatar answered Sep 05 '25 03:09

CD..