简体   繁体   中英

Push array into multidimension array in Javascript

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 )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM