[英]Javascript Array changes value when I push it onto another array
There's a strange thing happening in my code that I don't know the reason for. 我的代码中发生了一件奇怪的事情,我不知道原因。
I have 2 arrays. 我有2个数组。 One is a very large array (40,000 elements long) and one is an empty array. 一个是非常大的数组(长40,000个元素),一个是空数组。
I want to push the large array onto the empty array like so: 我想像这样将大数组推到空数组上:
emptyArray.push(largeArray);
This works as expected for the most part.... but some of the large Arrays values just vanish when I do the push. 这在大多数情况下都可以正常工作....但是当我执行推送时,一些大型Array值就消失了。 If before it was: 如果之前是:
largeArray = [0, 1, 2, 3, 4, 5, ..... ,40000]; largeArray = [0,1,2,3,4,5,.....,40000];
Now when I console.log it, it shows: 现在,当我进行console.log记录时,它显示:
largeArray = [0,1,3,4,5,....,40000];
The 2 is just gone. 2刚走了。 I double checked that the 2 was there prior to the push by using breakpoints and sure enough before the array gets pushed all it's values are there. 我使用断点仔细检查了2是否在推送之前在那里,并且在数组被推送之前确保所有值都足够确定。 When the array is pushed however, some just vanish. 但是,当推入阵列时,某些阵列就消失了。
Any ideas? 有任何想法吗? I tested my project on firefox and chrome, both show the same behavior. 我在firefox和chrome上测试了我的项目,两者都表现出相同的行为。 Also this is just normal javascript arrays, not typed arrays or anything. 而且这只是普通的javascript数组,而不是类型化数组或其他任何东西。
Some people in the comments asked for more details behind the code. 注释中的某些人要求提供代码背后的更多详细信息。 So this is a more through explanation. 因此,这是一个更透彻的解释。
I'm drawing an image on a canvas, then I get the image data. 我在画布上绘制图像,然后获取图像数据。 I only want to work with the red channel so I make a new array like so: 我只想使用红色通道,所以我制作了一个新的数组,如下所示:
var imgData = ctx.getImageData(0, 0, width, height);
var imgDataRed = [];
for (i = 0; i < imgData .length; i+=4) {
imgDataRed[i] = imgPixels[i / 4];
}
I then want to push this imgDataRed array onto an empty storage array. 然后,我想将此imgDataRed数组推入一个空的存储数组。 So I run: 所以我跑:
var storageArr = [];
storageArr.push(imgDataRed);
Hope that helps. 希望能有所帮助。
You can use this. 您可以使用它。
var storageArr = imgDataRed.slice(); var storageArr = imgDataRed.slice();
Basically slice() is the operation which is available in java script in order to copy and cut.. slice()基本上是在Java脚本中可用的操作,以便进行复制和剪切。
If you're working with big arrays, you should be looking at a library like immutable.js . 如果使用大型数组,则应该查看像immutable.js之类的库。
Here's a for example: 例如:
const { List } = require('immutable');
var arr1 = [];
for(var i=0; i<40000; i++){
arr1.push(i);
}
var list1 = List(arr1);
console.log(list1.count()); // outputs 40000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.