Search code examples
javascriptarraysretain

How to retain array in javascript?


Here's some code that has two arrays(np and op), one a copy of the other

However, when I modify the copy, the original is also modified! take a look:

<script type="text/javascript">
var op=new Array(0, 0);
var np=op;
np[1]=2;
document.write(op+"<br>")
document.write(np)
</script>

Is there any way to retain the original and modify the copy?


Solution

  • You never made a copy of the array. You simply assigned the array to another variable. This does not copy in Javascript. In your example there is only one array with two variables by which you can access it. There is no built-in way to copy arrays in Javascript so you will need to write your own function to do it.

    Take a look at this StackOverflow question for a hint on how to actually implement the copying of the elements in the array.