Joined September 2015
·

name

location
·
·

Posted to Why never use new Array in Javascript over 1 year ago

i find nothing wrong with new Array(N) and the examples you provided as "wrong" or "unexpected" are completely normal. if i want to allocate 20 spaces in a new array - that's exactly what is it for. if i push something in the array (that has already 20 indeces reserved), it gets pushed further. like you said, arrays are dynamic in javascript and that's the result of it.

an example use: we want to keep last N timestamps of something and then cycle through it if we run out of space. we comfortably define the size of the N in the array definition, without having to write conditions later, like this:

//... the definition
var last_stamps = new Array(20);


//... then somewhere later on some event ...
for(var i=0;i<last_stamps.length;i++){
    if(i<last_stamps.length-1){
        last_stamps[i]=last_stamps[i+1];
    }
}
last_stamps[last_page_stamps.length-1]=(new Date()).getTime();

like first-in last-out queue

Achievements
1 Karma
0 Total ProTip Views