Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for () loop variants

I'm creating this element with these attributes:

var x = document.createElement('x');
x.setAttribute('ha','1');
x.setAttribute('he','2');
x.setAttribute('hi','3');

And then I loop through it using these 2 forms, getting different output each time:

>>>for(var i in x.attributes) console.log(x.attributes[i]);
ha="1"
he="2"
hi="3"
3
item()
getNamedItem()
setNamedItem()
removeNamedItem()
getNamedItemNS()
setNamedItemNS()
removeNamedItemNS()

And the other one:

>>>for(var i=0;i<x.attributes.length;i++) console.log(x.attributes[i]);
ha="1"
he="2"
hi="3"

So, shouldn't this be giving the same result ? Why not ?

like image 777
weisk Avatar asked Sep 23 '26 04:09

weisk


2 Answers

This is because you are getting everything from the prototype as well. Use hasOwnProperty to only iterate over those properties that you have set:

for(var i in x.attributes){ 
    if (x.hasOwnProperty(i)) {
        console.log(x.attributes[i]);
    }
}

The for...in approach iterates through all the properties of an object, including the 'native' properties. To restrict the output to those properties you've defined:

for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
        console.log(i);
    }
}

References:

  • for...in.
  • hasOwnProperty().
like image 33
David Thomas Avatar answered Sep 24 '26 19:09

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!