justsomeguy Posted July 10, 2007 Share Posted July 10, 2007 I've got an issue where I'm trying to determine whether or not an object has been defined. I have the name of the object as a string. I can test for the type of the object using typeof and eval. If I have the object cmi.interactions defined, this will say "object":alert(typeof(eval("cmi.interactions")));If I am testing for a child object that I know is undefined, this will correctly return "undefined":alert(typeof(eval("cmi.interactions._0")));This says "undefined", which is good, that's what I want. That object is in fact undefined. However, when I try this:alert(typeof(eval("cmi.interactions._0.type")));That is an error, with the familiar message:message: Statement on line 1: Could not convert undefined or null to objectSo, it's fine when only the "final" object is not defined, but when the "final" object has a parent object that is also not defined (in this case _0), it's an error.Is there a way to test for this without having to break apart the string and test each object individually? Link to comment Share on other sites More sharing options...
jesh Posted July 11, 2007 Share Posted July 11, 2007 It would incur some overhead, but if parsing the string is out of the question, then you could try putting the code in a try/catch block. Link to comment Share on other sites More sharing options...
justsomeguy Posted July 11, 2007 Author Share Posted July 11, 2007 Yeah, I just ended up parsing the string. It seems to work fine. chunks = el.split("."); el_defined = true; i = 0; while (el_defined && i < chunks.length) { obj_str = ""; for (j = 0; j <= i; j++) { if (obj_str != "") obj_str += "."; obj_str += chunks[j]; } if (typeof(eval(obj_str)) == "undefined") el_defined = false; i++; } Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.