Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these loops different?

Tags:

javascript

I was working on my site at work, when I encountered something strange, I'm fetching data from a database via ajax, and then I uses some loops to update the data in a table. Here is my first attempt at the loop

for(var id in data){
    for(var key in data[id])
        for(var e in document.getElementsByName(key+id))
            e.innerHTML = data[id][key] !== null ? data[id][key] : "";

I expected that to work without a problem, but it doesn't. None of the fields in the table gets updated, and I have no idea why. Then I decided to test with something more traditional, and ended up with this.

for(var id in data){
    for(var key in data[id]){
        var temp = document.getElementsByName(key+id);
        for(var i=0; i<temp.length; i++)
            temp[i].innerHTML = data[id][key] !== null ? data[id][key] : "";
    }

That worked prefect, but I don't understand why, since from what I can see, the loops should do the same thing. So I wonder, why are they different, and how can I fix it. I like consistencies in my codes, and don't want to use the for(var i=0; i<temp.length; i++) since I used the other types of loops earlier.

like image 452
Yemto Avatar asked Feb 12 '23 16:02

Yemto


1 Answers

document.getElementsByName(key+id) returns an array. The syntax for(var x in y) iterates over names in an object/array. The names in an object are the keys, the names in an array is the index.

Hence, e in you last loop, will be 0, 1, 2, 3, length, ....

like image 87
Thor Jacobsen Avatar answered Feb 20 '23 02:02

Thor Jacobsen