如何在 JavaScript 中取消移位或添加到参数对象的开头
我刚刚学习了 弹出第一个元素的约定arguments 数组(我也学到了其实是一个Object).现在我需要做相反的事情.我需要使用 unshift 操作将值添加到 arguments 数组(或 Object 像数组一样)的开头.这可能吗?我试过了:
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);
这对 arguments 没有任何影响.
That had no effect on arguments whatsoever.
推荐答案
使用
.call()而不是.apply()来调用unshift()
将 arguments 设置为 unshift()
将 'hello' 设置为 unshift()
<小时>
Array.prototype.unshift.call(arguments, 'hello');
<小时>
正如@lonesomeday 所指出的,您可以使用 .apply() 而不是 .call(),但您需要传递一个类似数组的参数作为第二个争论.因此,在您的情况下,您需要将 '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.
相关文章