Thursday, July 07, 2005

from __future__ import * � Iteration in JavaScript

from __future__ import * � Iteration in JavaScript: "Iteration in JavaScript

In JavaScript, there are basically two kinds of object iteration:
* All objects support property enumeration for (var x in obj):
* Some objects support the 'Array protocol': for (var cnt; cnt < obj.length; cnt++)

These both suck.

Property enumeration is only really useful for debugging, since chances are the objects will have a lot of properties that you do not want them to have, and there is no standard way to have properties that are hidden from enumeration.

Array protocol enumeration sucks because:

* Writing for loops is so 'C'
* Not every object that supports the 'array protocol' is actually an array, so the 'higher order' methods to manipulate the array such as Array.prototype.slice aren't going to be available everywhere. DOM NodeList objects and the special arguments array are particularly common examples of these array-like objects.

Fortunately, this doesn't stop you from writing your own iteration protocol. Here is an example of a JavaScript iterator in the style of Python's PEP 234 - Iterators
"