array like objects

Mike Wilson mikewse at hotmail.com
Sat Dec 12 07:37:11 PST 2009


David-Sarah Hopwood wrote:
> Mark S. Miller wrote:
> > function isArrayLike(obj) {
> >   var len;
> >   return !!(obj &&
> >             typeof obj === 'object' &&
> >             'length' in obj &&
> >             !({}).propertyIsEnumerable.call(obj, 'length') &&
> >             (len = obj.length) >>> 0 === len);
> > }
>
> If you want to avoid side effects:
> 
> function isArrayLike(obj) {
>   if (!obj || typeof obj !== 'object') return false;
>   var desc = Object.getOwnPropertyDescriptor(obj, 'length');
>   if (desc) {
>     var len = desc.value;
>     return !desc.enumerable && (len === undefined || len >>> 
> 0 === len);
>   }
> }

An advantage with Mark's code is that it doesn't rely
on ES5 API. I think it's good to establish a standard
for array-likeness that can be matched by ES3 code as
well.

Best regards
Mike



More information about the es-discuss mailing list