How to change one variable without changing the other?

Asked

Viewed 509 times

1

When I copy a variable, if I change the copy, I change the first variable. How to change the value of the second without affecting the first ?

var cont = [10, 1, 3];

alert(cont.length + "\n");

var tmp_cont = cont;
tmp_cont.pop();

alert(cont.length + " : " + tmp_cont.length + "\n");

2 answers

3


The method slice, make a copy of the vector for you, generating 2 independent vectors.

var vector1 = [0,1,2,3,4,5];
var vector2 = vector1.slice();

vector2.pop();
alert(""+vector1.length+" : "+vector2.length);
  • It works. Thank you !

  • That’s what we’re here for!

3

In Javascript some guys have this behavior and variables that receive the guy are merely references to guy initial and not independent copies.

This is the case for objects, arrays and functions. But it is not the case for numbers, strings and booleans. The problem you describe in the question does not happen with these, also called primitive types.

To solve the problem, you have different options depending on the guy what you’re dealing with. For arrays you already have an alternative in another answer, you can also use other variants that also work for objects. For complex objects you can do with ideas of these answers, the simplest way (for objects or arrays only with Primitives) is

var b = JSON.parse(JSON.stringify(a));

To copy functions the simplest way is to use new, so you get a different instance, which shares the prototype.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.