1

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)

Daniel
  • 23
  • 3

1 Answers1

2

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}`);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • 1
    [I don't think JS uses pointers](https://stackoverflow.com/questions/17382427/are-there-pointers-in-javascript) (although I think this is an engine implementation detail) – evolutionxbox Jan 28 '21 at 10:56
  • no worries. I personally don't think it matters much, but I hope it helps – evolutionxbox Jan 28 '21 at 11:01