Can I call a function with multiple arguments in a convenient way in JavaScript?
example:
var fn = function() {
console.log(arguments);
}
var args = [1,2,3];
fn(args);
I need arguments to be [1,2,3] just like my Array.
Can I call a function with multiple arguments in a convenient way in JavaScript?
example:
var fn = function() {
console.log(arguments);
}
var args = [1,2,3];
fn(args);
I need arguments to be [1,2,3] just like my Array.
You should use apply:
var fn = function() {
console.log(arguments);
};
var args = [1,2,3];
fn.apply(null, args);
Apply will make the equivalent function call:
fn(1,2,3);
Notice that I used null as the first argument of apply, that will set the this keyword to the global object (window) inside fn.
Also you should know that the arguments object is not really an array, it's an array-like object, that contains numeric indexes corresponding to the arguments that were used to call your function, a length property that gives you the number of arguments used, and the arguments.callee property that is a reference to the executing function (useful for recursion on anonymous functions).
If you want to make an array from your arguments object, you can use the Array.prototype.slice method:
var fn = function() {
var args = Array.prototype.slice.call(arguments);
console.log(args);
};
Edit: In response to your comment, yes, you could use the shift method and set its returned value as the context (the this keyword) on your function:
fn.apply(args.shift(), args);
But remember that shift will remove the first element from the original array, and your function will be called without that first argument.
If you still need to call your function with all your other arguments you can:
fn.apply(args[0], args);
And if you don't want to change the context, you could simply extract the first argument inside your function:
var fn = function() {
var args = Array.prototype.slice.call(arguments),
firstArg = args.shift();
console.log(args, firstArg);
};