8

I've just learned the convention for popping off the first element of the arguments array (which I also learned is actually an Object). Now I need to do the opposite. I need to use an unshift operation to add a value to the beginning of the arguments array (or Object acting like an array). Is this possible? I tried:

Array.prototype.unshift.apply('hello', arguments);

That had no effect on arguments whatsoever.

3
  • You cannot modify the arguments collection. You can modify the argument values, but not the length of the collection etc. Commented Nov 11, 2013 at 18:51
  • @Pointy: Yes, you can modify its length. Commented Nov 11, 2013 at 18:53
  • @BlueSkies yes sorry; what I meant was that you can't mess with it like an array. Changing the length of an array affects array elements after the new length by making them undefined, but updating the length of the arguments object won't do that. I should have worded my comment more clearly. Commented Nov 11, 2013 at 18:57

1 Answer 1

21
  1. use .call() instead of .apply() to invoke unshift()

  2. set arguments as the this value of unshift()

  3. set 'hello' as the argument to unshift()


Array.prototype.unshift.call(arguments, 'hello');

As @lonesomeday pointed out, you can use .apply() instead of .call(), but you need to pass an array-like argument as the second argument. So in your case, you'd need to wrap 'hello' in an Array.

Sign up to request clarification or add additional context in comments.

2 Comments

You could also do apply(arguments, ['hello']).
This gives me a strange result in Chrome: ['hello', 'argument1', undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.