Javascript – Clone an Array

Here is a simple way to copy an array, which contains primitive data types like string and integer, by value in Javascript.

var myArray = ['eureka', 30, true];
var clone = myArray.slice(0);

myArray[1] = 100;
console.log(myArray[1]); // output: 100
console.log(clone[1]);   // output: 30

 

But if myArray contains objects, those objects will be copied by reference. So if you really want to have a deep copy method, add the following clone function to Array.prototype.

Array.prototype.clone = function() {
  return this.slice(0);
};

 

Now you could make a copy by.

var myArray = ['eureka', 30, true];
var realClone = myArray.clone();

 

Doe =)

Reference: David Walsh – Clone Arrays with JavaScript

http://davidwalsh.name/javascript-clone-array

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s