3

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 ?

weisk
  • 2,468
  • 1
  • 18
  • 18

2 Answers2

5

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:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
5

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]);
    }
}
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • What a wonderful example on when to **NOT** use a ternary oprator. Or, should I say, how to use it in a wrong way. – JustAPoring Nov 14 '12 at 11:00
  • @alro Oh does the code break? I didn't test it. I only used the ternary to make it obvious where he would include the test in his own logic. – Asad Saeeduddin Nov 14 '12 at 11:01
  • No, but it's simply not the intended usage of it. If you're just gonna do something ridiculous like `:void(0)`, you're better off just using an `if`. – JustAPoring Nov 14 '12 at 11:02
  • Just to explain the reason behind it and not just complain: The ternary operator returns a value, and it's used when you have to use either value X or Y in an expression or as a parameter. If you don't actually use the returned value, the if is the more intended and gentle way to do it. Either way, +1 for editing :) – JustAPoring Nov 14 '12 at 11:07
  • @alro I know, you should see how gruesomely I misuse the constructs in other C like languages. :P Thanks for the tip. – Asad Saeeduddin Nov 14 '12 at 11:09