Came across this code, and it had me scratching my head, and wondered is their benefits to grabbing the length to set the index.
var thisarray = new Array();
function addtoArray(int){
thisarray[thisarray.length] = int;
}
over array.push
function addtoArray(int){
thisarray.push(int)
}
Also, is there an equivalent to this php
thisarray[]
2 Answers 2
In the example you have posted, the two uses are the same. Both append a new element to the end of the array.
However, the push() method can take multiple arguments and so you can append multiple elements to the end of the array in one statement. push() then returns the new length of the array. push() is also shorter and arguably easier to read.
Another thing to consider is that if thisarray has been incorrectly defined (ie. it is not an Array object) then thisarray[thisarray.length] = int; is likely to fail silently since .length will simply be undefined. Whereas thisarray.push(int) will fail with a trappable TypeError exception.
Regarding PHP's thisarray[] (square bracket) syntax. There is nothing quite the same in JavaScript, as far as syntax goes. However, thisarray[thisarray.length] = int; performs the same action.
Comments
thisarray[thisarraylength] = int and thisarray.push(int) are identical. Arguably, the only advantage the latter has over the former is readability.
You might also find answers to this question useful: Why is array.push sometimes faster than array[n] = value?
thisarray[thisarray.length] = somethingis equivalent to PHP'sthisarray[] = something. Andpush()is equivalent toarray_push().