Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is javascript array index set by array length

Tags:

javascript

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[]
like image 264
madphp Avatar asked Sep 01 '26 15:09

madphp


1 Answers

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.

like image 62
MrWhite Avatar answered Sep 04 '26 07:09

MrWhite