How to change one variable without changing the other?

1

When I copy a variable, if I change the copy, I change the first variable accordingly. 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");
    
asked by anonymous 05.03.2016 / 02:44

2 answers

3

The method slice , makes 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);
    
05.03.2016 / 02:54
1

In JavaScript some types have this behavior, and variables that receive type are just references to the initial type p>

This is the case for objects, arrays, and functions. But it is not the case of 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 type you are dealing with. For arrays you already have an alternative other answer , you can also use other variants that also work for objects. For complex objects you can do ideas from these answers , the simplest way (for objects or primitive-only arrays) 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 prototype .

    
05.03.2016 / 10:02