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

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

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


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

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

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


当前回答

我使用了一个可以检查变量和对象的函数。使用jQuery非常方便

    function _isset (variable) {
        if(typeof(variable) == "undefined" || variable == null)
            return false;
        else
            if(typeof(variable) == "object" && !variable.length) 
                return false;
            else
                return true;
    };

其他回答

我总是使用这个泛型函数来防止基本变量以及数组和对象上的错误。

isset = function(obj) {
  var i, max_i;
  if(obj === undefined) return false;
  for (i = 1, max_i = arguments.length; i < max_i; i++) {
    if (obj[arguments[i]] === undefined) {
        return false;
    }
    obj = obj[arguments[i]];
  }
  return true;
};

console.log(isset(obj));                   // returns false
var obj = 'huhu';
console.log(isset(obj));                   // returns true
obj = {hallo:{hoi:'hoi'}};
console.log(isset(obj, 'niet'));           // returns false
console.log(isset(obj, 'hallo'));          // returns true
console.log(isset(obj, 'hallo', 'hallo')); // returns false
console.log(isset(obj, 'hallo', 'hoi'));   // returns true
if (var) {
  // This is the most concise equivalent of Php's isset().
} 
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;

 } 
//
//

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

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