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.
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.
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.
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.
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.
use .call()
instead of .apply()
to invoke unshift()
set arguments
as the this
value of unshift()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With