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 ?

1

2 Answers 2

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]);
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

What a wonderful example on when to NOT use a ternary oprator. Or, should I say, how to use it in a wrong way.
@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.
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.
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 :)
@alro I know, you should see how gruesomely I misuse the constructs in other C like languages. :P Thanks for the tip.
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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.