Lets take a look at this code:
var mainFunction = function() {
altFunction.apply(null, arguments);
}
The arguments that are passed to \"mainF
One liner to add additional argument(s) and return the new array:
[].slice.call(arguments).concat(['new value']));
The arguments
"array" isn't an array (it's a design bug in JavaScript, according to Crockford), so you can't do that. You can turn it into an array, though:
var mainFunction = function() {
var mainArguments = Array.prototype.slice.call(arguments);
mainArguments.push('extra data');
altFunction.apply(null, mainArguments);
}
For those who like me was looking for a way to add an argument that is optional and may be not the only omitted one (myFunc = function(reqiured,optional_1,optional_2,targetOptional)
with the call like myFunc(justThisOne)
), this can be done as follows:
// first we make sure arguments is long enough
// argumentPosition is supposed to be 1,2,3... (4 in the example above)
while(arguments.length < argumentPosition)
[].push.call(arguments,undefined);
// next we assign it
arguments[argumentPosition-1] = arguments[argumentPosition-1] || defaultValue;
var mainFunction = function() {
var args = [].slice.call( arguments ); //Convert to array
args.push( "extra data");
return altFunction.apply( this, args );
}
Update 2016: You must convert the arguments to an array before adding the element. In addition to the slice method mentioned in many posts:
var args = Array.prototype.slice.call(arguments);
You can also use the Array.from() method or the spread operator to convert arguments to a real Array:
var args = Array.from(arguments);
or
var args = [...arguments];
The above may not be optimized by your javascript engine, it has been suggested by the MDN the following may be optimized:
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments