I would like to do this:
if(abc) alert('c exists') //produces error if(a && ab && abc ) alert('c exists') //also produces ReferenceError
The only way I know this (EDIT: This is apparently the only way):
if(typeof(a) != "undefined" && ab && abc) alert('c exists');
or some type of function like this ...
if(exists('abc')) alert('c exists'); function exists(varname){ vars=varname.split('.'); for(i=0;i<vars.length;i++){ //iterate through each object and check typeof } } //this wont work with local variables inside a function
EDIT: SOLUTION BELOW (Credit on this topic from Felix, I adapted it a little Check if a member object exists in a nested object )
It works:
if (typeof a != 'undefined' && ab && abc) alert('c exists')
But the best I have found is to include it in a function. I use two different functions: one to get a variable depth in the object, and one to check if its set is set.
function getprop(obj, path_string) { if(!path_string) return obj var arr = path_string.split('.'), val = obj || window; for (var i = 0; i < arr.length; i++) { val = val[arr[i]]; if ( typeof val == 'undefined' ) return false; if ( i==arr.length-1 ) { if (val=="") return false return val } } return false; } function isset(obj, path_string) { return (( getprop(obj, path_string) === false ) ? false : true) }
javascript
timh
source share