On Mar 17, 2:01 am, Michael Geary <[email protected]> wrote:
> 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[...]
>
> > (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)
And even if the specification changes, it will take quite some time
before it can be relied upon on the web
> 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.
No, you can't. There is an old version of Opera that returned
properties in alphabetic order. Try this in various browsers:
(function() {
// Just a helper
function show(t, o) {
var s = [];
for (var p in o) {
s.push(p);
}
alert(t + s);
}
function filteredShow(t, o) {
var s = [];
for (var p in o) {
if (p in obj) {
s.push(p);
}
}
alert(t + s);
}
// Create an object
var obj = {};
// Add some properties in order
obj.first = 'first';
obj.second = 'second';
obj.third = 'third';
obj.fourth = 'fourth';
// What oder do they come back in?
show('Are they in order?\n', obj);
// Ok, how about the window object
s = [];
for (var p in obj) {
window[p] = obj[p];
}
// Is this the same order? In all browsers?
// Firefox will have reversed the order
filteredShow('Are they still in order with window?\n', window);
// How about another host object
var div = document.createElement('div');
for (var p in obj) {
div[p] = obj[p];
}
filteredShow('Are they still in order with DOM element?\n', div);
// How about deleted and re-added properties
delete obj.first;
// Is first gone?
show('Check first is deleted:\n', obj);
// Add it again
obj.first = 'first';
// What is the order now? IE adds first back at the start,
// others add it at the end
show('Where is first now?\n', obj);
})();
Behaviour is not consistent, different browsers have different quirks
- no surprises there. ;-)
--
Rob
--
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]