Reputation: 18041
We're developing a javascript-based GIS application and everything was going fine until someone decided to fire up IE9 and gave it a spin over there too. As you have probably already guessed, the app broke down.
Turned out that for some inexplicable reason for..in
loop is unable to iterate over childNodes
:
var xmldoc = new ActiveXObject("Msxml2.DOMDocument.6.0");
xmldoc.loadXML("<i18n><item>one</item><item>two</item></i18n>");
var currentItem = xmldoc.getElementsByTagName("i18n")[0].firstChild;
while (currentItem) {
if (currentItem.nodeType == 1) {
for (var i in currentItem.childNodes) {
console.log(currentItem.childNodes[i]);
}
}
currentItem = currentItem.nextSibling;
}
However, when the internal for
loop in above code is replaced with
for (var j = 0; j < currentItem.childNodes.length; j++) {
console.log(currentItem.childNodes[j]);
}
everything works as expected - it walks the child nodes without any issues.
Although I discovered a workaround, the issue still annoys me as it is not clear why it happens. MSDN documentation both for XMLDocument and for..in mentions nothing.
Is this a bug or another case of poorly-documented oddness that IE is famous of?
Upvotes: 0
Views: 309
Reputation: 168685
Short answer: Don't use for..in
to iterate arrays. Arrays should always be iterated with a for()
loop. Only non-array objects should use for...in
.
If you must use a for..in
here, you should filter the loop using .hasOwnProperty()
to prevent unwanted iterations on properties that belong to the array prototype rather than the array itself.
This point applies to all for..in
loops: to ensure your code is robust, you should get into the habit of always filtering them with .hasOwnProperty()
, even on plain objects, but especially on arrays, since we already know they contain additional properties.
See here for more on this point.
Upvotes: 2
Reputation: 140220
Well, it's not a bug since DOM spec doesn't define that there should be numeric properties, just the item
method which []
desugars to.
Simply don't use for..in
.
Upvotes: 2