0

I have really weird situation:

when I do that code:

var origin_array = [1,2,3];
var m = origin_array;
m.pop();

alert(origin_array);

origin_array value will be 1,2 eventhough I didn't changed it

but if I make that code:

var x = 5;
var y = x;
y--;

alert(x);

x still be 5, it won't be connected to "x" as you can see from the 1st example.

So my question is how do I make the "m" array unique, which not change the origin array?

Daniel
  • 147
  • 1
  • 2
  • 9

2 Answers2

2

You need to explicitly make a (shallow) copy or clone of origin_array:

var m = origin_array.slice(0);

This is not needed for primitive values, such as strings and numbers.

It's important to understand that although the above will prevent the issue you were experiencing, the same may happen again deeper down if you're dealing with more complex structures, and in some cases a "deep clone" is necessary.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

Arrays are assigned by reference. That means that when you do this:

var origin_array = [1,2,3];
var m = origin_array;

m just points to the exact same array as origin_array. There is only one array and both origin_array and m point to it. If you modify it via either variable, they will both see the modification because you're modifying the one array that they both point to.

In javascript, both objects and arrays are assigned by reference like this. Assigning them does NOT make a copy. If you want an assignment to generate a copy, you have to explicitly make a copy. For an array, that is easy as you can just do:

var origin_array = [1,2,3];
var m = origin_array.slice(0);  // makes a shallow copy
m.pop();
console.log(origin_array);      // [1,2,3] because origin_array was not changed
jfriend00
  • 683,504
  • 96
  • 985
  • 979