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

javascript: List of array methods that change the array they were applied to - Stack Overflow

programmeradmin3浏览0评论

I constantly have problem with keeping this in my head, and I can't google it out quickly. That's why I'm putting this question here.

Every time I'm calling a method like concat, sort or slice, I'm asking myself: does it create and return a new array, or it just modifies and returns array it was applied to?

Q: could you please list methods that change the original array vs methods that construct and return a new array?

Methods like pop or push are not in the game, it's obvious what they do.

I constantly have problem with keeping this in my head, and I can't google it out quickly. That's why I'm putting this question here.

Every time I'm calling a method like concat, sort or slice, I'm asking myself: does it create and return a new array, or it just modifies and returns array it was applied to?

Q: could you please list methods that change the original array vs methods that construct and return a new array?

Methods like pop or push are not in the game, it's obvious what they do.

Share Improve this question asked Dec 13, 2013 at 16:23 DanDan 57.9k44 gold badges122 silver badges162 bronze badges 3
  • 3 MDN lists Array methods grouped under Mutator, Accessor, and Iteration. – Jonathan Lonowski Commented Dec 13, 2013 at 16:28
  • 1 Also, this is a likely duplicate of Which JavaScript Array functions are mutating?. – Jonathan Lonowski Commented Dec 13, 2013 at 16:42
  • Does this answer your question? Which JavaScript Array functions are mutating? – Krzysztof Kaczyński Commented Apr 18, 2022 at 23:37
Add a ment  | 

1 Answer 1

Reset to default 17

The full list of methods on array instances that change the values or number of values in the array is this one:

  • Array.prototype.push
  • Array.prototype.pop
  • Array.prototype.shift
  • Array.prototype.unshift
  • Array.prototype.splice
  • Array.prototype.reverse
  • Array.prototype.sort
  • Array.prototype.fill
  • Array.prototype.copyWithin

Aditionally, changing the length property can remove elements from the array (if you decrease it) or add undefined items to the array (if you increase it).

Finally, changing the properties of the arrays with keys that are positive integer-like strings like '0','1', '3000', etc will change the values at those indexes and possibly increase the length of the array.

发布评论

评论列表(0)

  1. 暂无评论