Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 arrays changing instead of 1

Tags:

javascript

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]

like image 887
i have a question Avatar asked Jun 12 '18 06:06

i have a question


1 Answers

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);
like image 57
Ankit Agarwal Avatar answered Oct 03 '22 02:10

Ankit Agarwal