我如何检查js链变量是否存在?

时间:2014-02-08 06:18:54

标签: javascript jquery

我如何检查js链var是否存在?任何简单的方法来检查或使用jquery
请看下面的代码:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    // how can i check a var exists ?
    // the code bellow will return undefined
    // a is undefined
        // a.b is undefined --- when a exists, then I need to check a.b
            // a.b.c is undefined  ...
                // a.b.c.d is undefined
    // sometimes I need to check if some property of an object exists or is true, and I don't even know the object exists or not
    // how can I check it then ?
    if(a.b.c.d){
        alert('yes');
    }
</script>

6 个答案:

答案 0 :(得分:4)

使用if条件随着嵌套级别的增加而变得笨拙。 使用此实用程序功能,可以完美地适用于任何级别的嵌套对象。

function checkExists( val, names ) {
    names = names.split( '.' );    
    while ( val && names.length ) { val = val[ names.shift() ]; }    
    return typeof val !== 'undefined';
}

<强>用法

if ( checkExists( a, 'b.c.d' ) ) {
    // operate on a.b.c.d
}

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

答案 1 :(得分:3)

你可以使用布尔运算符:

if(a && a.b && a.b.c && a.b.c.d){
    alert('yes');
}

在评论中,有人指出,如果a.b.c.d是“falsy”(0false,空字符串或空数组,则警告不会打印,即使该属性存在。因此,做到这一点的一个铁定方法是:

if(a && a.b && a.b.c && typeof a.b.c.d !== 'undefined'){
    alert('yes');
}

感谢short-circuit evaluation,这不会引发错误。

答案 2 :(得分:2)

if((typeof a !== 'undefined') && (typeof a.b !== 'undefined') && (typeof a.b.c !== 'undefined') && (typeof a.b.c.d !== 'undefined')){
        alert('yes');
}

使用&amp;&amp; (AND条件)当单个条件失败时,条件检查立即停止。因此,如果未定义,则不会进行其他检查。

答案 3 :(得分:0)

if (typeof a !== 'undefined' && a.b !== undefined && a.b.c !== undefined && a.b.c.d !== undefined)
alert('yes')

答案 4 :(得分:0)

我认为最好的方法是捕捉错误

ngDriver.FindElement(NgBy.)

答案 5 :(得分:0)

此功能将用于检查是否已定义a.b.c以及检查a.b [1] .d

let isDefined = (baseObject, varChian) => {
    try{
        if(typeof varChian != "undefined"){
            return eval(`baseObject.${varChian} != undefined`);
        }
        return typeof baseObject != "undefined";
    }catch(e){
        return false;
    }
}

然后您可以通过

调用它
isDefined(a, "b[1].c");
isDefined(a);
isDefined(a, "b.c")
相关问题