Array#copy – Useful JavaScript Game Extensions #21

It’s not unheard of to want to copy an array. Though usually you’d prefer to use map, select, or reject, sometimes you just need your own copy. Fortunately the copy method is extremely easy to implement by leveraging the existing Array#concat method.

* Creates and returns a copy of the array. The copy contains
* the same objects.
* @type Array
* @returns A new array that is a copy of the array
Array.prototype.copy = function() {
  return this.concat();  

Array#concat glues arrays together and returns the result. If you call it with many arguments the contents of each argument are appended and returned as a new resulting array. If you call it with zero arguments you still get a new resulting array, just no additional items are appended, so it makes a great copy.

Leave a Reply

Your email address will not be published. Required fields are marked *