2 arrays changing instead of 1

  • A+
Category:Languages

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);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: