哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))

if (elem) { // or !elem

or

if (typeof elem !== 'undefined') {

or

if (elem != null) {

当前回答

为了有助于辩论,如果我知道变量应该是字符串或对象,我总是喜欢if(!variable),所以检查它是否是假的。这可以带来更干净的代码,例如:

if(数据类型!==“undefined”&&数据类型。url===“未定义”){var message='接收响应时出错';if(typeof data.error!==“undefined”){message=数据错误;}否则如果(数据类型.消息!==“未定义”){message=数据消息;}警报(消息);}

..可以简化为:

if(data&&!data.url){var message=data.error | | data.message | |'接收响应时出错';警报(消息)}

其他回答

您需要运算符的类型。明确地:

if (typeof variable !== 'undefined') {
    // the variable is defined
}
if (typeof console != "undefined") {    
   ...
}

或者更好

if ((typeof console == "object") && (typeof console.profile == "function")) {    
   console.profile(f.constructor);    
}

适用于所有浏览器

我很惊讶这还没有被提及。。。

以下是使用此['var_name']的一些其他变体

使用此方法的好处是,它可以在定义变量之前使用。

if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part

// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!

为了使if条件正确工作,我们必须使用关键字let来创建变量。

let name = undefined; 
if (name) { 
    alert('valid')
};

这取决于您是否只关心变量是否已定义,或者是否希望它具有有意义的值。

检查类型是否未定义将检查变量是否已定义。

==空或!==null将仅检查变量的值是否完全为null。

==空或!=null将检查该值是否未定义或为null。

if(value)将检查变量是否为undefined、null、0或空字符串。