如何检查另一个对象内部的变量是否设置(js)?

tim*_*imh 6 javascript

我想这样做:

if(a.b.c) alert('c exists')   //produces error
if(a && a.b && a.b.c ) alert('c exists')   //also produces ReferenceError
Run Code Online (Sandbox Code Playgroud)

我知道这样做的唯一方法(编辑:这显然是唯一的方法):

if(typeof(a) != "undefined" && a.b && a.b.c) alert('c exists');
Run Code Online (Sandbox Code Playgroud)

或某种类似的功能......

if(exists('a.b.c')) 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
Run Code Online (Sandbox Code Playgroud)

编辑:解决方案以下 (由Felix信任此线程,我只是稍微调整了一下 检查对象成员是否存在于嵌套对象中)

这有效:

if (typeof a != 'undefined' && a.b && a.b.c) alert('c exists')
Run Code Online (Sandbox Code Playgroud)

但我发现的最好的事情就是把它放到一个函数中.我使用了2个不同的函数,一个用于在对象中获取变量,另一个用于检查其是否设置.

/**
 * Safely retrieve a property deep in an object of objects/arrays
 * such as userObj.contact.email
 * @usage var email=getprop(userObj, 'contact.email')
 *      This would retrieve userObj.contact.email, or return FALSE without
 *      throwing an error, if userObj or contact obj did not exist
 * @param obj OBJECT - the base object from which to retrieve the property out of
 * @param path_string STRING - a string of dot notation of the property relative to
 * @return MIXED - value of obj.eval(path_string), OR FALSE
 */
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;
}

/**
 * Check if a proprety on an object exists
 * @return BOOL
 */
function isset(obj, path_string)
{
    return (( getprop(obj, path_string) === false ) ? false : true)
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 6

试试这个:

if (a && a.b && a.b.c)
Run Code Online (Sandbox Code Playgroud)


Šim*_*das 3

这个怎么样:

function exists(str, namespace) {
    var arr = str.split('.'),
        val = namespace || window;

    for (var i = 0; i < arr.length; i++) {
        val = val[arr[i]];
        if ( typeof val == 'undefined' ) return false;
    }
    return true;    
}
Run Code Online (Sandbox Code Playgroud)

现场演示: http: //jsfiddle.net/Y3KRd/