简体   繁体   中英

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)

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));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM