简体   繁体   English

如何在JavaScript中取消移位或将其添加到arguments对象的开头

[英]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没有任何影响。

  1. use .call() instead of .apply() to invoke unshift() 使用.apply() .call()而不是.apply()来调用unshift()

  2. set arguments as the this value of unshift() arguments设置为unshift()this

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM