majidarif
majidarif

Reputation: 19985

Appending to agrument object in javascript

The arguments variable returns an object like:

console.log(arguments)
=> { '0': 'arg1', '1': function[] }

What if I wanted to append to that and shift everything to the right?

{ '0': 'add', '1': 'arg1', '2': function[] }

How can I achieve this? Manually or with underscoreJS

Useful info with underscore:

oArray_.toArray(list)

Creates a real Array from the list (anything that can be iterated over). Useful for transmuting the arguments object.

Did something like:

var args = _.toArray(arguments)
args.unshift(fn)

Upvotes: 2

Views: 54

Answers (2)

Bergi
Bergi

Reputation: 664538

You can apply the Array unshift method on the arguments object:

Array.prototype.unshift.call(arguments, "add");

However, it's better not to mess with the arguments object. Rather convert it to an array, prepend "add" to that, and use it instead of arguments in your function body:

var args = ["add"].concat(Array.prototype.slice.call(arguments));
var args = ["add"].concat(_.toArray(arguments));

Upvotes: 6

Carl Younger
Carl Younger

Reputation: 3070

The arguments object isn't a real array. It's a JS thing. Convert it to an array first.

Upvotes: 0

Related Questions