On Wed, Mar 16, 2011 at 4:42 AM, Peter van der Zee <[email protected]>wrote:

> ... In fact, for-in is not meant to iterate an array but will instead
> iterate all "properties" of the array. Note that an array is nothing more
> than a regular object with some special stuff to it. Hence, for-in will
> treat it exactly the same as any other object and will not only return you
> the index properties (0, 1, 2, etc) but also other properties (like length)
> and inherited properties (like prototype's push, pop, etc). So, never use
> for-in to iterate over an array unless this was what you wanted. Always use
> for (var i ... ++i) or the array lambda family (forEach, map, filter, etc).
>

for-in will generally not enumerate .length, .push(), or the like, because
those are marked as non-enumerable.

It *will*, however, enumerate any other properties or methods added to the
array itself or to Array.prototype, and for that reason it should not be
used on an array (unless of course you *want* to see those extra
properties).


> (Note that the order of for-in might look stable but is not specified to be
> stable. There's some discussion to change that right now but for the time
> being, don't rely on it)
>

While you shouldn't use it on an array, for-in on an *object* returns
property names in the same order in which they were added to the object.
There wasn't any specification for this other than the fact that browsers
have to do it this way to avoid breaking websites that assume this behavior.
Maybe some non-browser implementation does it differently, bur you can count
on this in any browser.

-Mike

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to