Jump to content

Typeof undefined objects


justsomeguy
 Share

Recommended Posts

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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...