Why are these loops different?

I worked on my site at work, when I came across something strange, I retrieve data from the database via ajax, and then I use some loops to update the data in the table. Here is my first loop attempt

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 to work without problems, but it is not. None of the fields in the table are updated, and I have no idea why. Then I decided to try something more traditional, and in the end it turned out.

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] : "";
    }

This worked as a prefect, but I don’t understand why, because from what I see, the loops should do the same. Therefore, I wonder why they are different, and how I can fix it. I like the consistency in my codes and don’t want to use for(var i=0; i<temp.length; i++), since I used other types of loops before.

+4
3

var e document.getElementsByName(key+id)

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

document.getElementsByName(key+id) . for(var x in y) /. , - .

, e 0, 1, 2, 3, ,....

+8

In the first example, you made 2 mistakes.

  • do not follow for .. infor arrays. Because you will iterate not by indexes, but by properties.
  • in your case is enot an element, but an index. Why is this not working.
0
source

All Articles