weisk
weisk

Reputation: 2540

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 ?

Upvotes: 3

Views: 903

Answers (2)

user1726343
user1726343

Reputation:

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]);
    }
}

Upvotes: 5

David Thomas
David Thomas

Reputation: 253318

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:

Upvotes: 5

Related Questions