Inconsistent implementation of the for ... in loop.
I ran into a hard-to-find bug today. After a while I figured out that IE cleared one of my hashes, for seemingly no good reason. This was my code:
for (var p in hash) { hash["x_" + p] = hash[p]; delete hash[p]; }
I actually didn’t manage to reproduce this behavior outside of my original script, instead IE would go into an infinite loop and rapidly claim all available memory when the code ran.
It turns out that ECMA-262 has the following to say about the for … in loop (section 12.6.4): The mechanics of enumerating the properties […] is implementation dependent. […] If new properties are added to the object being enumerated during enumeration, the newly added properties are not gauranteed to be visited in the active enumeration.
So for IE 6 and 7 the decision was to include new properties, while firefox does not. I haven’t tried the other browsers.
So, don’t delete properties on objects you are iterating through!
I still haven’t figured out why my initial code behaved in the way it did (deleting all properties), hopefully I won’t run into that problem again.
Post new comment