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[]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With