Monday, 12 June 2017
javascript - Pass unknown number of parameters to JS function
Answer
Answer
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?
Answer
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
Subscribe to:
Post Comments (Atom)
c++ - Does curly brackets matter for empty constructor?
Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...
-
A fair amount of the second act of The Dark Knight Rises has a class warfare plotline. This is foreshadowed in the trailers with Selina Ky...
-
I'm still trying to wrap my head around how the following expression results in undefined behavior: a = a++; Upon searching SO...
-
i have added this sql in my code , function devenir_client_dataforform() { $type = $_POST['clientType']; //$produit...
No comments:
Post a Comment