Check if array key exists via the in operator
-
The in operator doesn't seem to be acting like I would expect. In this snippet of code it should be printing 0 but it always prints 1.
var myObj = {pie:"apple", cake:"chocolate", sausage:"dog"}; if ("fish" in myObj) { Console.print(1); } else { Console.print(0); }
-
Yeah, the
in
operator is only used for the iterator loop.But you can test if the key exists like this:
var myObj = {"pie":"apple", "cake":"chocolate", "sausage":"dog"}; inline function keyExists(obj, key) { return !(obj[key] == void); // Important: not undefined! } if (keyExists(myObj, "fish")) { Console.print(1); } else { Console.print(0); }
-
Thank you :)