array like objects

Mike Wilson mikewse at hotmail.com
Fri Dec 11 12:08:42 PST 2009


Mark S. Miller wrote:



If we're looking for a convention that is 
* does not admit any legacy ES3R non-array non-host objects (to prevent
false positives)
* does easily allow ES5 programmers to define new array-like non-array
objects
* takes bounded-by-constant time (i.e., no iteration)
* is a reasonably compatible compromise with the existing notions of
array-like in legacy libraries as represented by previous examples in this
thread


then I suggest:


function isArrayLike(obj) {
  var len;
  return !!(obj &&
            typeof obj === 'object' && 
            'length' in obj && 
            !({}).propertyIsEnumerable.call(obj, 'length') && 
            (len = obj.length) >>> 0 === len);
}

Thanks Mark, this is the right way to approach it I think. String objects
will be considered array-like above which may not be desired, but either
way, I think it is this type of guideline that can prove valuable, so host
objects and libraries can make sure to adhere (or make sure not to adhere)
to that pattern. I'm not sure where it should be put, but maybe there should
be an official ES "duck" page with committee approved patterns ;-).
 
Best regards
Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20091211/65224a1b/attachment.html>


More information about the es-discuss mailing list