Count array: length ok?

Hello,

I’ve always used .length to count the elements of an array. I’ve see people doing it in a much more complex way, though.

Is length ok, or am I exposed to some security issue?

:slight_smile:

Yes, using .length is the best way to do it when dealing with arrays.

Perhaps if you show us some of the other complex ways you’ve seen though, we can help to explain the different circumstances in which they might be of good use.

//An array can have a length and fewer than that (or no) defined items-


var A= [1, 2, 3];
A.length= 200;

alert(A.join(', ')+'\
'+A.length);
/*  returned value: (String)
1, 2, 3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 
200
*/

For example, php.js has quite a complicated approach… But I guess it takes into account objects?

:slight_smile:

It does, yes - because it’s trying to simulate in JavaScript the way length can be used in PHP. That’s something that’s not relevant to normal JavaScript usage.