[whatwg] Adding ECMAScript 5 array extras to HTMLCollection

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 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 Monday, 26 April 2010 10:04:18 UTC