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.

Community
  • 1
  • 1
at.
  • 50,922
  • 104
  • 292
  • 461
  • You cannot modify the `arguments` collection. You can modify the argument values, but not the length of the collection etc. – Pointy Nov 11 '13 at 18:51
  • @Pointy: Yes, you can modify its length. – Blue Skies Nov 11 '13 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. – Pointy Nov 11 '13 at 18:57

1 Answers1

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.

Blue Skies
  • 2,935
  • 16
  • 19
  • 1
    You could also do `apply(arguments, ['hello'])`. – lonesomeday Nov 11 '13 at 18:55
  • 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]` – piotr_cz Jan 22 '15 at 11:43