Javascript Data Type How to - Make a Copy of an array








Question

We would like to know how to make a Copy of an array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--  w  ww. j  a v  a2  s .  c  o m-->
var Mycollection1 = new Array("James", "Jonh", "Mary");
var Mycollection2 = Mycollection1.slice();
Mycollection1.pop();
document.writeln(Mycollection1.toString()) // ["James","Jonh"]
document.writeln('<br/>');
document.writeln(Mycollection2.toString()) // ["James","Jonh", "marry"]

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: