Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript add extra argument

Tags:

javascript

Let's take a look at this code:

var mainFunction = function() {   altFunction.apply(null, arguments); } 

The arguments that are passed to mainFunction are dynamic -- they can be 4 or 10, doesn't matter. However, I have to pass them through to altFunction AND I have to add an EXTRA argument to the argument list.

I have tried this:

var mainFunction = function() {   var mainArguments = arguments;   mainArguments[mainArguments.length] = 'extra data'; // not +1 since length returns "human" count.    altFunction.apply(null, mainArguments); } 

But that does not seem to work. How can I do this?

like image 744
onlineracoon Avatar asked Nov 28 '12 17:11

onlineracoon


People also ask

What happens if you pass an extra parameter to a method in JavaScript?

Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.

Do I always have to add parameters to every function in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help.

What is args in JS?

args is a rest parameter. It always has to be the last entry in the parameter list and it will be assigned an array that contains all arguments that haven't been assigned to previous parameters. It's basically the replacement for the arguments object. Instead of writing function max() { var values = Array. prototype.

Can callback function have parameters?

Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.


2 Answers

Use Array.prototype.push

[].push.call(arguments, "new value"); 

There's no need to shallow clone the arguments object because it and its .length are mutable.

(function() {     console.log(arguments[arguments.length - 1]); // foo      [].push.call(arguments, "bar");      console.log(arguments[arguments.length - 1]); // bar })("foo"); 

From ECMAScript 5, 10.6 Arguments Object

  1. Call the [[DefineOwnProperty]] internal method on obj passing "length", the Property Descriptor {[[Value]]: len, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}, and false as arguments.

So you can see that .length is writeable, so it will update with Array methods.

like image 131
I Hate Lazy Avatar answered Oct 08 '22 12:10

I Hate Lazy


arguments is not a pure array. You need to make a normal array out of it:

var mainArguments = Array.prototype.slice.call(arguments); mainArguments.push("extra data"); 
like image 31
VisioN Avatar answered Oct 08 '22 11:10

VisioN