I'm facing weird situation while trying to perform simple operation of pushing array into multidimension array. Here is a code:
var Atest = Array();
var Btest = ([0, 0, 0, 0]);
Btest[0] = 1;
Btest[1] = 2
Btest[2] = 3;
Btest[3] = 4;
Atest.push([Btest]);
Btest[0] = 11;
Btest[1] = 12;
Btest[2] = 13;
Btest[3] = 14;
Atest.push([Btest]);
document.write("<br>" + Atest);
And I'm expecting to get the following output:
1,2,3,4,11,12,13,14
However, I'm getting unexpected output:
11,12,13,14,11,12,13,14
What I'm missing?
(PS: Found similar unanswered question asked ~5 years ago: pushing new array into a 2d array)
1 Answer 1
When you push Btest into Atest you push a pointer to the Btest array.
You need to copy the underlying values contained inside of Btest.
Example using the spread operator which will create a copy of the data :
const Atest = Array();
const Btest = ([0, 0, 0, 0]);
Btest[0] = 1;
Btest[1] = 2
Btest[2] = 3;
Btest[3] = 4;
Atest.push([...Btest]);
Btest[0] = 11;
Btest[1] = 12;
Btest[2] = 13;
Btest[3] = 14;
Atest.push([...Btest]);
document.write(`<br>${Atest}`);
answered Jan 28, 2021 at 10:55
Orelsanpls
23.7k7 gold badges46 silver badges74 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
evolutionxbox
I don't think JS uses pointers (although I think this is an engine implementation detail)
evolutionxbox
no worries. I personally don't think it matters much, but I hope it helps
lang-js
Btestare being modified twice.atest.concat(btest);