array like objects

Mike Samuel mikesamuel at gmail.com
Mon Dec 7 17:33:20 PST 2009


It occurred to me after looking at the proxy strawman that it might
help to nail down what "array-like" means in future drafts.  It isn't
directly related to the proxy stuff though so I thought I'd start a
separate thread.

I've seen quite a bit of library code that does something like
   if (isArrayLike(input)) {
     // iterate over properties [0,length) in increasing order
   } else {
     // Iterate over key value pairs
   }
but different libraries defined array-like in different ways.
Some ways I've seen:
    (1) input instanceof Array
    (2) Object.prototype.toString(input) === '[object Array]'
    (3) input.length === (input.length >> 0)
etc.

The common thread with array like objects is that they are meant to be
iterated over in series.
It might simplify library code and reduce confusion among clients of
these libraries if there is some consistent definition of series-ness.
This committee might want to get involved since it could affect
discussions on a few topics:
   (1) key iteration order
   (2) generators/iterators
   (3) catchall proposals
   (4) type systems

One strawman definition for an array like object:
    o is an array like object if o[[Get]]('length') returns a valid
array index or one greater than the largest valid array index.

The need to distinguish between the two in library code could be
mooted if for (in) on arrays iterated over the array index properties
of arrays in numeric oder order first, followed by other properties in
insertion order, and host objects like NodeCollections followed suit.


More information about the es-discuss mailing list