[英]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
). 我刚刚了解了弹出arguments
数组的第一个元素的约定 (我也实际上是一个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). 我需要使用unshift
操作将一个值添加到arguments
数组的开头(或Object
作用类似于数组)。 Is this possible? 这可能吗? I tried: 我试过了:
Array.prototype.unshift.apply('hello', arguments);
That had no effect on arguments
whatsoever. 这对arguments
没有任何影响。
use .call()
instead of .apply()
to invoke unshift()
使用.apply()
.call()
而不是.apply()
来调用unshift()
set arguments
as the this
value of unshift()
将arguments
设置为unshift()
的this
值
set 'hello'
as the argument to unshift()
将'hello'
设置为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. 正如@lonesomeday指出的,可以使用.apply()
代替.call()
但需要传递类似阵列的参数作为第二个参数。 So in your case, you'd need to wrap 'hello'
in an Array. 因此,在您的情况下,您需要将'hello'
包装在数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.