Strange result using "for(in... " iteration

Joined
Jan 6, 2022
Messages
21
Reaction score
0
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.

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>
 
Joined
Sep 4, 2022
Messages
136
Reaction score
16
hello !



by the 'for (n) in arr' , you are reading array properties and its own content.
it returns your array custom settings, and all vars in. it makes more datas to fetch.

to avoid weird feedbacks stay on 'for loop'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,015
Messages
2,570,294
Members
46,910
Latest member
Steffen595

Latest Threads

Top