简体   繁体   中英

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:

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!

Is there a solution?

Here JsFiddle

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()

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

Demo: Fiddle


//test
var arr = [];
arr[50] = 1;
console.log('arr.length', arr.length);

will print 51 not 1

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