JavaScript Array Clone

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.

JavaScript Array Clone

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