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)

3
  • 1
    The values of Btest are being modified twice. Commented Jan 28, 2021 at 10:55
  • 1
    you should use atest.concat(btest); Commented Jan 28, 2021 at 10:55
  • This is because arrays are mutable, so you need to deep clone while pushing to a new array Commented Jan 28, 2021 at 10:59

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think JS uses pointers (although I think this is an engine implementation detail)
no worries. I personally don't think it matters much, but I hope it helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.