6

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?

Smash
  • 513
  • 5
  • 23

4 Answers4

5

Use slice() to copy the values to the new array:

var m2 = m1.slice(0);
Julio
  • 2,261
  • 4
  • 30
  • 56
2

Use Array.prototype.slice to copy arrays:

var m2 = m1.slice();
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

you need to do

var m2 = m1.slice(0);

The reason is that doing = copy the reference, slice will create a new array !

Shryme
  • 1,572
  • 1
  • 14
  • 22
1

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?

Community
  • 1
  • 1
Sean Doe
  • 277
  • 2
  • 9