[whatwg] Adding ECMAScript 5 array extras to HTMLCollection

On Jul 29, 2010, at 9:03 PM, Alex Russell wrote:

> On Mon, Apr 26, 2010 at 10:04 AM, David Flanagan
> <david at davidflanagan.com> wrote:
>> Erik Arvidsson wrote:
>>>>> 
>>>>> for (var i = 0, length = collection.length; i < length; i++)
>>>>> // instead of:
>>>>> for (var i = 0; i < collection.length; i++)
>>>>> 
>>>> Actually, the former is a problem when the nodelist is modified in the
>>>> loop; it may result in collection[i] being undefined.
>>> 
>>> Even when checking the length in every iteration you can run into
>>> problems. If you remove something earlier in the collection you will
>>> *miss* one item unless you fix the loop iterator.
>>> 
>>> We should not let these edge cases get in the way of making the DOM
>>> collections feel less foreign to JavaScript.
>>> 
>>> --
>>> erik
>>> 
>> 
>> Rather that trying to make DOM collections feel like arrays, how about just
>> giving them a toArray() method?
> 
> This is pretty terrible. For lack of a way to subtype Arrays in the
> language, we're going to contort the entire DOM API (again) to do
> unnatural things? The right answer here is to make an immutable length
> Array type/trait/interface and just define the various flavors of HTML
> collection in those terms.

The various html collections aren't fixed length, they're not assignable, so they can't used interchangeably with arrays at the best of times.

> Support for doing this needs to be one of TC39's highest priority
> tasks, and indeed the work on proxies is going to make it possible in
> Harmony. No need to screw up the DOM any more than it already has
> been.

I'm not sure how you expect proxies to help here but for the record all array functions defined in ES5 are "generic" in that they work over any array-like object.  So Array.prototype.forEach.apply(myHTMLCollection, function(...){...}) will work.  This is obviously not as elegant as might be liked and TC39 is (or at least was) considering putting generic methods onto the Array constructor, eg. Array.forEach(arrayLike, callback)

--Oliver

Received on Thursday, 29 July 2010 21:43:51 UTC