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

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

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


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

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

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


当前回答

function isset(variable) {
    try {
        return typeof eval(variable) !== 'undefined';
    } catch (err) {
        return false;
    }
}

其他回答

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

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

在ES6中要小心,如果你想检查let变量的声明并声明它,那么之前的所有解决方案都是无效的

例子

let myTest = 'text';

if(typeof myTest === "undefined") {
    var myTest = 'new text'; // can't be a let because let declare in a scope
}

您将看到一个错误

标识符'myTest'已经声明

解决办法是用一个变量

var myTest = 'text'; // I replace let by a var

if(typeof myTest === "undefined") {
    var myTest = 'new text';
}

另一个解决方案是,如果你可以通过一个变量来改变一个let,你需要删除你的变量

let myTest = 'text';

if(typeof myTest === "undefined") {
    myTest = 'new text'; // I remove the var declaration
}
//
//  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;

 } 
//
//

尝试在Javascript中创建类似PHP的空函数。 希望这能有所帮助。

function empty(str){
  try{
    if(typeof str==="string"){
        str=str.trim();
    }
    return !(str !== undefined && str !== "undefined" && str !== null && str!=="" && str!==0 && str!==false);
  }catch(ex){
    return true;
  }
 }

console.log(empty(0))//true
console.log(empty(null))//true
console.log(empty(" "))//true
console.log(empty(""))//true
console.log(empty(undefined))//true
console.log(empty("undefined"))//true

var tmp=1;
console.log(empty(tmp))//false

var tmp="Test";
console.log(empty(tmp))//false

var tmp=" Test ";
console.log(empty(tmp))//false

var tmp={a:1,b:false,c:0};
console.log(empty(tmp.a))//false
console.log(empty(tmp.b))//true
console.log(empty(tmp.c))//true
console.log(empty(tmp.c))//true
console.log(empty(tmp.c.d))//true

我通常使用typeof操作符:

if (typeof obj.foo !== 'undefined') {
  // your code here
}

如果属性不存在或其值未定义,则返回“undefined”。

(参见:未定义和未定义的区别。)

还有其他方法来确定一个属性是否存在于一个对象上,比如hasOwnProperty方法:

if (obj.hasOwnProperty('foo')) {
  // your code here
}

和in操作符:

if ('foo' in obj) {
  // your code here
}

最后两个方法的区别在于,hasOwnProperty方法将检查该属性是否在对象上物理存在(该属性没有继承)。

in操作符将检查原型链中所有可达的属性,例如:

var obj = { foo: 'bar'};

obj.hasOwnProperty('foo'); // true
obj.hasOwnProperty('toString'); // false
'toString' in obj; // true

如你所见,在检查toString方法时,hasOwnProperty返回false, in操作符返回true,这个方法是在原型链中定义的,因为obj继承了Object.prototype的形式。