I had the same question as posed here: Checking if an associative array key exists in Javascript .
However, I'm looking for a method which will work in all major browsers including IE 6+. The method I saw which I liked is the use of the in
operator, which I've never seen before.
I tried something different in google chrome which seemed to work, but I'd like to know why its not used instead of the in
operator.
For reference:
var data = {foo : "bar"};
console.log("foo" in data); // true
console.log("bar" in data); // false
My proposal:
var data = {foo : "bar"};
console.log(!!data.foo); // true
console.log(!!data.bar); // false
Are there any drawbacks with my (second) method?
var data = {foo: 0};
orvar data = {foo: false};
orvar data = {foo: ''};
. Of course if you know that your object will never contain such values, you are fine. But general solutions should work without any assumptions. – Felix Kling Aug 5 '12 at 19:36in
, see stackoverflow.com/questions/2920765/… – bfavaretto Aug 5 '12 at 19:40