在PHP中,你可以这样做if(isset($array['foo'])){…}。在JavaScript中,你经常使用if(array.foo){…}来做同样的事情,但这不是完全相同的语句。条件也将计算为false if数组。Foo确实存在,但为false或0(也可能为其他值)。

JavaScript中与PHP的isset完美对应的是什么?

从更广泛的意义上说,一个关于JavaScript如何处理不存在的变量、没有值的变量等的通用的、完整的指南会很方便。


更新:11年零11个月前,我发布了这个问题,哇,它仍然有很多活动。现在,我非常确定,当我写这篇文章时,我只是想知道如何检查关联数组(也就是字典)中属性的存在,因此(对我来说)正确的答案涉及hasOwnProperty或in操作符。我对检查局部或全局变量不感兴趣。

但是,虽然我记得很清楚,但在写的问题中,这种意图并不十分清楚,甚至与之直接矛盾!我还没提到关联数组,PHP的isset也有其他功能。让这成为我们所有人的一个教训,让我们知道在一个问题中正确地陈述你的要求是多么重要,以及全局变量、局部变量、对象属性、字典键和其他什么东西是多么重要。

与此同时,很多很多人也提供了这个问题的答案,所以对于那些通过谷歌找到这个问题的人来说,我很高兴我的含糊在某种程度上有所帮助。不管怎样,我只是想澄清一下。


当前回答

要检查html块是否存在,我使用以下代码:

if (typeof($('selector').html()) != 'undefined') {
    // $('selector') is existing
    // your code here
}

其他回答

function isset(variable) {
    try {
        return typeof eval(variable) !== 'undefined';
    } catch (err) {
        return false;
    }
}
//
//  tring to reference non-existing variable throws ReferenceError 
//  before test function is even executed
//
//  example, if you do:
//    
//     if ( isset( someVar ) ) 
//        doStuff( someVar );
//   
//  you get a ReferenceError ( if there is no someVar... ) 
//  and isset fn doesn't get executed.
//
//  if you pass variable name as string, ex. isset( 'novar' );, 
//  this might work:
//
function isset ( strVariableName ) { 

    try { 
        eval( strVariableName );
    } catch( err ) { 
        if ( err instanceof ReferenceError ) 
           return false;
    }

    return true;

 } 
//
//

将此函数用于数组或嵌套数组(但不适用于字符串)

if(isset(array,'key1=>key1')){alert('isset');}

https://jsfiddle.net/dazzafact/cgav6psr/

arr={nested:{nested2:{val:'isset'}}}
if(t=isset(arr,'nested=>nested2=>val','=>')){
   alert(t)
}
function isset(obj,nested,split) {
var sep=split || '.';
    var dub=obj
    var isset=false
    if(typeof(obj)!="undefined" && typeof(nested)!="undefined"){
        var arr=nested.split(sep);
        for(var k in arr){
            var key=arr[k];
            if(typeof(dub[key])=="undefined"){
                isset=false;
                break;
            }
            dub=dub[key];
      isset=dub
        }   
    }
    
    return isset;
}
try {
  const value = array.foo.object.value;
  // isset true
} catch (err) {
  // isset false
}

如果你想检查一个元素是否存在,只需使用下面的代码:

if (object) {
  //if isset, return true
} else {
  //else return false
}

这是样本:

function switchDiv() { if (document.querySelector("#divId")) { document.querySelector("#divId").remove(); } else { var newDiv = document.createElement("div"); newDiv.id = "divId"; document.querySelector("body").appendChild(newDiv); } } document.querySelector("#btn").addEventListener("click", switchDiv); #divId { background: red; height: 100px; width: 100px; position: relative; } <body> <button id="btn">Let's Diiiv!</button> </body>