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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

为了检查变量是否已被声明/设置,我使用了这个肮脏的技巧。

即使使用eval,我也没有找到将代码提取到函数的方法。点击下面的评论,了解原因。

"use strict";

// var someVar;

var declared;
try {
  someVar;
  declared = true;
} catch(e) {
  declared = false;
}

if (declared) {
  console.log("someVar is declared; now has the value: " + someVar);
} else {
  console.log("someVar is not declared");
}

其他回答

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

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可以将未定义的变量减少为单个字符,每次都可以节省几个字节。

Null是JavaScript中的值,typeof Null返回“object”

因此,如果您传递空值,则接受的答案将不起作用。如果传递空值,则需要为空值添加额外的检查:

if ((typeof variable !== "undefined") && (variable !== null))  
{
   // the variable is defined and not null
}

很难区分undefined和null。Null是一个值,当您想要指示变量没有特定值时,可以将其赋值给该变量。未定义是一个特殊值,它将是未分配变量的默认值。


var _undefined;
var _null = null;

alert(_undefined); 
alert(_null); 
alert(_undefined == _null);
alert(_undefined === _null);

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

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

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

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

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

我的首选是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)