[英]Function shift() doesn't work inside loop
I'm trying to manipulate an array inside a for loop, where I want to add an item to the end of the array and delete an element at the beginning of the array, like this: 我正在尝试在for循环内操作数组,在这里我想在数组的末尾添加一个项目,并在数组的开头删除一个元素,如下所示:
var internal = new Array();
for(var i = 0; i < 1000; i++) {
internal[i] = Math.floor(Math.random() * 37);
internal.shift();
console.log(internal.length);
}
The problem is that it looks like shift() doesn't work inside the loop, in fact, no element is deleted from the array! 问题在于,看起来shift()在循环内不起作用,实际上,没有从数组中删除任何元素!
Is there a solution? 有解决方案吗?
It reduces by one every time, but you are growing it every time by accessing it with the array index accessing. 每次它减少一倍,但是每次通过数组索引访问来访问它时,它每次都在增长。 Instead of
代替
internal[i] = Math.floor(Math.random() * 37);
use 采用
internal.push(Math.floor(Math.random() * 37));
For example, 例如,
var internal = [];
internal[3] = "thefourtheye";
console.log(internal);
Output 输出量
[ , , , 'thefourtheye' ]
It made space for the first three elements and added the element at the index specified. 它为前三个元素留出空间,并在指定的索引处添加了该元素。 So, it will keep the array growing.
因此,它将保持阵列的增长。
Note: Use []
to create a new array, instead of new Array()
注意:使用
[]
创建一个新数组,而不是new Array()
because you are using a hard coded index, try 因为您使用的是硬编码索引,请尝试
var internal = new Array();
for(var i = 0; i < 1000; i++) {
internal.push(Math.floor(Math.random() * 37));
internal.shift();
console.log(internal.length);
}
//test
var arr = [];
arr[50] = 1;
console.log('arr.length', arr.length);
will print 51
not 1
将打印
51
而不是1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.