Home Java Javascript-array JavaScript Array Clone
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

JavaScript Array Clone

Advertisement
As you know, the property 'prototype' of Array class can add and modify the properties and methods of the array.

JavaScript Array Clone

     

As you know, the property 'prototype' of Array class can add and modify the properties and methods of the array. You can see in the given example that we have used the property prototype to use clone() method. Prototype extends all native JavaScript arrays with few methods. The method arr1.clone() returns the duplicate of the array. It copies the elements of the specified array.

Here is the code for creating clone of array in JavaScript..

<html>
<head>
<h2>
Use of Clone() method
</h2>
<script type="text/javascript">
Array.prototype.clone = function () {
var arr1 = new Array(); 
for (var property in this) {
arr1[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]
}
return arr1;
}
arr1 = ["Rose", "India", "Technologies"];
arr2 = arr1.clone();
document.write("<b>The First Array is: </b>"+arr1+"<br>");
document.write("<b>After using clone() method, the array is copied: </b>"+arr2);
</script>
</head>
<body bgcolor="lightBlue">
</body>
</html>

Output will be displayed as:

Download Source Code

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 11, 2008

Ask Questions?    Discuss: JavaScript Array Clone   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
hak
July 24, 2012
Simpe solution

if(!Array.prototype.clone){ Array.prototype.clone = function clone() { return this; } } b = [1,2,3].clone();
DMCA.com