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

min*_*004 1 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>
Run Code Online (Sandbox Code Playgroud)

gur*_*deb 6

if((typeof a !== 'undefined') && (typeof a.b !== 'undefined') && (typeof a.b.c !== 'undefined') && (typeof a.b.c.d !== 'undefined')){
        alert('yes');
}
Run Code Online (Sandbox Code Playgroud)

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

使用 ES2020(Chrome 80+、Firefox 74+),您可以进行可选链接

if(a?.b?.c?.d) alert('yes');
Run Code Online (Sandbox Code Playgroud)


Shi*_*ula 5

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

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

用法

if ( checkExists( a, 'b.c.d' ) ) {
    // operate on a.b.c.d
}
Run Code Online (Sandbox Code Playgroud)

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