最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - How to unshift or add to the beginning of arguments object in JavaScript - Stack Overflow

programmeradmin1浏览0评论

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);

That had no effect on arguments whatsoever.

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);

That had no effect on arguments whatsoever.

Share Improve this question edited May 23, 2017 at 12:32 CommunityBot 11 silver badge asked Nov 11, 2013 at 18:51 at.at. 52.5k105 gold badges303 silver badges470 bronze badges 3
  • You cannot modify the arguments collection. You can modify the argument values, but not the length of the collection etc. – Pointy Commented Nov 11, 2013 at 18:51
  • @Pointy: Yes, you can modify its length. – Blue Skies Commented Nov 11, 2013 at 18:53
  • @BlueSkies yes sorry; what I meant was that you can't mess with it like an array. Changing the length of an array affects array elements after the new length by making them undefined, but updating the length of the arguments object won't do that. I should have worded my comment more clearly. – Pointy Commented Nov 11, 2013 at 18:57
Add a comment  | 

1 Answer 1

Reset to default 21
  1. use .call() instead of .apply() to invoke unshift()

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

  3. set 'hello' as the argument to 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. So in your case, you'd need to wrap 'hello' in an Array.

发布评论

评论列表(0)

  1. 暂无评论