如何在 JavaScript 中取消移位或添加到参数对象的开头

How to unshift or add to the beginning of arguments object in JavaScript

本文关键字:添加 参数 对象 开头 位或 JavaScript 取消      更新时间:2023-09-26

我刚刚学会了弹出arguments数组第一个元素的约定(我还了解到这实际上是一个Object)。现在我需要做相反的事情。我需要使用 unshift 操作将值添加到arguments数组的开头(或Object像数组一样)。这可能吗?我试过了:

Array.prototype.unshift.apply('hello', arguments);

这对arguments没有任何影响。

  1. 使用 .call() 而不是 .apply() 来调用unshift()

  2. arguments设置为 unshift()this

  3. 'hello'设置为要unshift()的参数


Array.prototype.unshift.call(arguments, 'hello');

正如@lonesomeday指出的,您可以使用.apply()而不是.call(),但是您需要传递一个类似数组的参数作为第二个参数。因此,在您的情况下,您需要将'hello'包装在数组中。