Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unshift or add to the beginning of arguments object in JavaScript

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.

like image 800
at. Avatar asked Nov 11 '13 18:11

at.


People also ask

How do you add an item to the beginning of a list in JavaScript?

Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to push() method but it adds an element at the beginning of the array.

How do you Unshift an object in JavaScript?

JavaScript unshift() Method: Array ObjectThe unshift() method is used to add one or more elements to the beginning of an array and return the length of the array. The elements to add to the front of the array. Example: In the following web document, unshift() method adds two elements at the beginning of a given array.

How do you push to the beginning of an array?

Answer: Use the unshift() Method You can use the unshift() method to easily add new elements or values at the beginning of an array in JavaScript. This method is a counterpart of the push() method, which adds the elements at the end of an array. However, both method returns the new length of the array.

How do you shift and Unshift?

The shift() method in JavaScript removes an item from the beginning of an array and shifts every other item to the previous index, whereas the unshift() method adds an item to the beginning of an array while shifting every other item to the next index.


1 Answers

  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.

like image 107
Blue Skies Avatar answered Sep 19 '22 05:09

Blue Skies