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.
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, ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With