How to unshift or add to the beginning of arguments object in JavaScript
10,100
use
.call()
instead of.apply()
to invokeunshift()
set
arguments
as thethis
value ofunshift()
set
'hello'
as the argument tounshift()
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.
Author by
at.
Updated on July 29, 2022Comments
-
at. almost 2 years
I've just learned the convention for popping off the first element of the
arguments
array (which I also learned is actually anObject
). Now I need to do the opposite. I need to use anunshift
operation to add a value to the beginning of thearguments
array (orObject
acting like an array). Is this possible? I tried:Array.prototype.unshift.apply('hello', arguments);
That had no effect on
arguments
whatsoever. -
lonesomeday over 10 yearsYou could also do
apply(arguments, ['hello'])
. -
piotr_cz over 9 yearsThis 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]