How can I change a value ONLY of arreglo2
without changing arr
?
var arr = [0, 1, 2, 3, 4];
var arreglo2 = arr;
arreglo2[1] = "Hola";
console.log(arr);
console.log(arreglo2);
(In both the position 1 was modified).
How can I change a value ONLY of arreglo2
without changing arr
?
var arr = [0, 1, 2, 3, 4];
var arreglo2 = arr;
arreglo2[1] = "Hola";
console.log(arr);
console.log(arreglo2);
(In both the position 1 was modified).
I think you're messing around unnecessarily, because what you say is not true:
let a=1;
let b=a;
a=2;
console.log(a);
console.log(b);
The behavior you mention occurs with objects:
let a= { atributo: 0}
let b= a;
b.atributo=1;
console.log(a.atributo);
console.log(b.atributo);
And the reason is quite simple: Modifying the value of a variable is not the same as modifying the value of an attribute.
In the first case you have a primitive value, although for the case in question it is the same as if it were an object: 1 is a value and 2 is another. When a points to 1, and b points to 1, both variables point to the same place. When b happens to point to 2, a does not change.
In the second case a points to an object that has an attribute. Then b points to the same object. If I modify the object (but I do not modify what the variables point to), both variables continue pointing to the same object and, therefore, both see the change reflected.
You need to create an object equal to the original (clone) and save it in another variable:
let a=[1,2,3];
let b=a.slice();
b.push(4);
console.log(a);
console.log(b);
Using slice()
you can do it:
var arr = [0, 1, 2, 3, 4];
var arreglo2 = arr.slice();
arreglo2[1] = "Hola";
console.log(arr);
console.log(arreglo2);
This what it does is that it returns a new instance of the array. If you do not specify an index, the entire array is copied.
Another valid solution, based on the fixes are objects
We can do the following:
var arr = [0, 1, 2, 3, 4];
var arreglo2 = Object.values(arr);
arreglo2[0] = "lero lero"
console.log(arr,arreglo2)