Reputation: 513
I need to copy one array and remove the element, but only from second array?
for example:
var m1 = [ "a","b","c","d"];
var m2 = m1;
alert(m1+' and '+m2); // "a b c d" and "a b c d"
m2.splice(0,1); // b c d
alert(m1 + ' and ' + m2); // b c d and b c d
so the first element from each of these arrays was removed, but how to leave the 1st array static?
Upvotes: 6
Views: 10528
Reputation: 2290
Use slice()
to copy the values to the new array:
var m2 = m1.slice(0);
Upvotes: 5
Reputation: 275
When you assign m2 to m1, you assign reference to m2 variable. Both variables points to the same place in memory. You have to copy object.
Here is explanation how to do it in JavaScript: How do I correctly clone a JavaScript object?
Upvotes: 1
Reputation: 1570
you need to do
var m2 = m1.slice(0);
The reason is that doing = copy the reference, slice will create a new array !
Upvotes: 1