[英]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:我期待得到以下 output:
1,2,3,4,11,12,13,14
However, I'm getting unexpected output:但是,我得到了意想不到的 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 ) (PS:发现了大约 5 年前提出的类似未回答的问题: 将新数组推入二维数组)
When you push Btest
into Atest
you push a pointer to the Btest
array.当您将
Btest
推入Atest
时,您会将指针推入Btest
数组。
You need to copy the underlying values contained inside of Btest
.您需要复制
Btest
中包含的基础值。
Example using the spread operator
which will create a copy of the data:使用将创建数据副本的
spread operator
的示例:
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}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.