[Javascript] JS Array test

Jonathan Buchanan jonathan.buchanan at gmail.com
Wed Jun 25 04:14:30 CDT 2008


On Wed, Jun 25, 2008 at 8:33 AM, JS Student
<tuofamerikazmostwanted at gmail.com> wrote:
> Hi,
>
> I use the following piece of code to test if an element (el) is an
> array. Can anybody please suggest some improvemnts or point out any
> errors? So far it's been working fine for me but I just wanted to get
> some expert opinion on.
>
>
> /**CODE BEGIN**/
> if ((typeof(el)=="object")
>               && (typeof(el.length)=="number")
>               && ((el.length==0) || (!(el[0]===undefined)))) {
>
>              //Perform array operations
>
> }
>
> /**CODE END**/
>
>
> Regards,
>
> Aaron

Are you looking to for array-like objects (such as an Array or a
Function's "arguments" object) rather than just Arrays, as your method
above appears to be doing?

Your code fails to identify an Array or array-like if its first
element is undefined, is this intentional? Sticking it in an isArray
function, I get the following results:

>>> isArray([])
true
>>> isArray("")
false
>>> (function() { return isArray(arguments); })()
true
>>> (function() { return isArray(arguments); })(undefined)
false
>>> isArray([undefined])
false
>>> isArray([undefined, 1, 2, 3, 4, 5])
false
>>> isArray({"0": "toast"})
false
>>> isArray({length: 1, "0": "toast"})
true
>>> isArray({length: 1, "0": undefined})
false

Personally, I would drop the check for .length being 0 or [0] being
undefined, as it causes your method to fail on inputs which are
actually array-like, as shown above. Note that you're also matching
Objects with properties which appear to be array-like - this is fine
if you're not expecting to be able to call Array methods.

If you're actually looking for instances of Array (say, so you know
you can safely call Array methods such as "slice", which you couldn't
do directly on a Funciton's "arguments" object) then you could just
use "el instanceof Array," but without knowing _why_ you're checking
for array-like objects, I couldn't add much more at this stage :)

Regards,
Jonathan.



More information about the Javascript mailing list