Using the "in" operator in conditionals
Most of us are familiar with the for..in loop construct:
for (var i in object) { /* some iterative action here */ }
Less well-known is the use of "in" as an operator to test if a named property exists on an object:
>>> var x = {foo:1, bar:2, baz:'cat'}; >>> ('foo' in x) true >>> ('bar' in x) true >>> ('qux' in x) falseThis works on methods, too:
>>> ('toString' in x) true
It's particularly neato for testing the existence of properties with values that could be interpreted as false:
>>> var x = {foo:null, bar:false, baz:0}; >>> (x.foo) null >>> ('foo' in x); true >>> (x.bar) false >>> ('bar' in x) true
5 Comments:
Wow, that's great. Thanks for documenting this.
Watch out for testing the non-existing of properties.
E.g.
>>var o = {};
>>(!"a" in o)
false
Why? Because the ! operator takes precedence, so it evaluates to
>>(false in o)
false
Hence you must do
>>(!("a" in o))
true
Thanks.. never heard about this before. Next question.. Is this supported by all browsers?
I have tested in all 5 main browsers (IE,Chrome,Opera,Safari,Firefox) with the same results. I am fairly sure that this point flows from the ECMAScript specification itself and the operator precedence rules. Just an easy one to overlook (for me at least)!
I think you should probably be using
>> a.hasOwnProperty('foo')
instead of
>> ('foo' in a)
The 'in' also returns True for inherited properties which might not be what you want.
Post a Comment
<< Home