I am making a game with 2 arrays but one array changes when I don't want it to. Example from the console in browser:
A=[1,2,3,4,5]
B=[6,7,8,9,10]
A=B
A.push(11)
A =[6, 7, 8, 9, 10, 11]
B =[6, 7, 8, 9, 10, 11]
the A is fine but is there a way to make the B stay [6,7,8,9,10]
Use spread syntax as A=[...B];
to copy B
to A
. As when you do A=B
you are actually setting the reference of B
to A
so any changes to A
result in changes in B
and vice-versa.
var A=[1,2,3,4,5];
var B=[6,7,8,9,10];
A=[...B];
A.push(11);
console.log(A);
console.log(B);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With