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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

typeof运算符将检查变量是否真的未定义。

if (typeof variable === 'undefined') {
    // variable is undefined
}

与其他运算符不同,typeof运算符在与未声明的变量一起使用时不会引发ReferenceError异常。

但是,请注意,typeof null将返回“object”。我们必须小心避免将变量初始化为null的错误。为了安全起见,我们可以使用以下方法:

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}

有关使用严格比较==而不是简单相等==的更多信息,请参阅:JavaScript比较中应该使用哪个相等运算符(==vs==)?

其他回答

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

以下是使用此['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!

尝试捕捉

如果根本没有定义变量(例如:定义全局变量的外部库尚未加载-例如谷歌地图),您可以使用try-catch块检查这一点,无需中断代码执行,如下所示(不需要使用严格模式)

尝试{未定义变量;}捕获(e){console.log('检测到:变量不存在');}console.log('但代码仍在执行');未定义变量;//没有try-catch包装器代码在此处停止console.log('代码执行停止。您不会在控制台上看到此消息');

奖金:(参考其他答案)为什么==比==更清楚(来源)

如果(a==b)

如果(a===b)

我的首选是typeof(elem)!='未定义'&&elem!=无效的

无论您选择什么,请考虑将检查放入这样的函数中

function existy (x) {
    return typeof (x) != 'undefined' && x != null;
}

如果您不知道变量已声明,请继续使用typeof(x)!='未定义'&&x!=无效的

如果您知道变量已声明但可能不存在,可以使用

existy(elem) && doSomething(elem);

您正在检查的变量有时可能是嵌套属性。您可以使用prop | |{}来检查问题属性的存在性:

var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;

在每个属性之后,使用(…“| |{}”).nexPro,以便丢失的属性不会引发错误。

或者,您可以使用existy,如existy(o)&&exist(o.p)&&existiny(o.p.q)&&doSomething(o.p.q)

在大多数情况下,您会使用:

elem != null

与简单的if(elem)不同,它允许0、false、NaN和“”,但拒绝null或undefined,这使它成为一个很好的通用测试,用于检查参数或对象属性的存在。


其他检查也没有错,它们只是有不同的用途:

if(elem):如果elem被保证是一个对象,或者如果false、0等被认为是“默认”值(因此相当于undefined或null),则可以使用。typeof elem==“undefined”可用于指定的null对未初始化的变量或属性具有不同含义的情况。如果没有声明elem(即没有var语句,不是window的属性,或者不是函数参数),这是唯一不会抛出错误的检查。在我看来,这是相当危险的,因为它会让错别字不知不觉地溜走。要避免这种情况,请参阅以下方法。


与未定义的严格比较也很有用:

if (elem === undefined) ...

但是,由于全局undefined可以用另一个值重写,因此最好在使用变量之前在当前范围中声明变量undefined:

var undefined; // really undefined
if (elem === undefined) ...

Or:

(function (undefined) {
    if (elem === undefined) ...
})();

此方法的第二个优点是JS minifiers可以将未定义的变量减少为单个字符,每次都可以节省几个字节。

if (typeof console != "undefined") {    
   ...
}

或者更好

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

适用于所有浏览器