[whatwg] Adding ECMAScript 5 array extras to HTMLCollection

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.

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.

>?This makes it clear that a collection is
> not an array, but clearly defines a way to obtain an array. ?Clever
> implementors might even be able to optimize common uses-cases using some
> kind of copy-on-write strategy so that toArray() doesn't involve memory
> allocation and copying.
>
> Of course, trying to teach programmers when they ought to call toArray() and
> when it is not necessary is another matter. ?Perhaps calling the method
> snapshot() and focusing on the live vs. static distinction instead of the
> fake array vs. true array distinction would invite less misuse.
>
> Or we can just leave the DOM as it is and get used to calling the equivalent
> of Prototype's $A() function.
>
> ? ? ? ?David
>

Received on Thursday, 29 July 2010 21:03:46 UTC