To the code:
<!DOCTYPE html>
<html>
<body>
<p>This.........</p>
<p>That.....</p>
<p>And yet .....</p>
<script>
x=document.getElementsByTagName("p");
for (i in x)
document.write("..."+x[i].innerHTML+" "+i+"<br>");
document.write(x.length);
</script>
</body>
</html>
i'm getting the output
This.........
That.....
And yet .....
...This......... 0
...That..... 1
...And yet ..... 2
...undefined item
...undefined namedItem
...undefined iterator
...undefined length
3
rather than the following which is what i expect:
This.........
That.....
And yet .....
...This......... 0
...That..... 1
...And yet ..... 2
3
the for-in statement is supposed to iterate on x as many times as the length of x-- which is 3 as the code itself is saying-- and terminate. what it seems to be doing instead is iterating on all the children of the node-- not just the paragraph tags returned by document.getElementsByTagName("p").
this is either some subtlety i'm missing in the code, or a mistake in the JavaScript engine.
What's missing here?
forloop.for..infor iterating arrays or sequences.for..initerates properties (which includes array indexes, but also other properties likeitemanditerator).the for-in statement is supposed to iterate on x as many times as the length of x- Wrong. That is not what thefor ... instatement means at all. It iterates over the keys ofx.