In playing around with iteration methods I stumbled across this confusing outcome.
Method 1 code with a standard loop has the expected array property length of 2 and alerts for each pet but the second method using a "for(in …” iteration gives an extra 3 alerts . So it seems “arr” has extra (undefined) items. Hope someone can tell me why.
And, yes, I’m using JS to write the HTML elements instead of hard coding them.
Method 1 code with a standard loop has the expected array property length of 2 and alerts for each pet but the second method using a "for(in …” iteration gives an extra 3 alerts . So it seems “arr” has extra (undefined) items. Hope someone can tell me why.
And, yes, I’m using JS to write the HTML elements instead of hard coding them.
Code:
<script>
function go(){
arr=document.getElementsByClassName("pet");
alert("method 1")
for(i=0;i<arr.length;i++) // 2 alerts
{alert(arr[i].innerHTML)} // show contents
alert('method 2');
for ((n) in arr) // 5 alerts
{alert(arr[n].innerHTML)} // show contents
}
document.write
("<div class='pet' hidden>dog</div>\
<div class='pet' hidden>cat</div>\
<button onclick=go()>click to run</button>")
</script>