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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

尝试捕捉

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

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

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

如果(a==b)

如果(a===b)

其他回答

您可以使用typeof运算符。

例如

var dataSet;

alert("Variable dataSet is : " + typeof dataSet);

上面的代码段将返回如下输出

变量dataSet为:undefined。

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

如何检查变量是否存在

这是一个非常可靠的解决方案,用于测试变量是否存在并已初始化:

var setOrNot = typeof variable !== typeof undefined;

它最常用于与三元运算符结合使用,以在某个变量尚未初始化的情况下设置默认值:

var dark = typeof darkColor !== typeof undefined ? darkColor : "black";

封装问题

不幸的是,您不能简单地将检查封装在函数中。

你可能会想到这样做:

function isset(variable) {
    return typeof variable !== typeof undefined;
}

然而,如果您正在调用例如isset(foo),并且尚未定义变量foo,这将产生引用错误,因为您无法将不存在的变量传递给函数:

未捕获引用错误:未定义foo


测试函数参数是否未定义

虽然我们的isset函数不能用于测试变量是否存在(原因如上所述),但它确实允许我们测试函数的参数是否未定义:

var a = '5';

var test = function(x, y) {
    console.log(isset(x));
    console.log(isset(y));
};

test(a);

// OUTPUT :
// ------------
// TRUE
// FALSE

即使没有将y的值传递给函数测试,我们的isset函数在这种情况下也能很好地工作,因为在函数测试中y是一个未定义的值。

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

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

在JavaScript中,可以定义变量,但保持值未定义,因此最常见的答案在技术上不正确,而是执行以下操作:

if (typeof v === "undefined") {
   // no variable "v" is defined in the current scope
   // *or* some variable v exists and has been assigned the value undefined
} else {
   // some variable (global or local) "v" is defined in the current scope
   // *and* it contains a value other than undefined
}

这可能足以满足你的目的。以下测试具有更简单的语义,这使得准确描述代码的行为并自己理解它变得更容易(如果您关心这些事情):

if ("v" in window) {
   // global variable v is defined
} else {
   // global variable v is not defined
}

当然,这假设您在浏览器中运行(其中window是全局对象的名称)。但如果你在摆弄这样的全局变量,你很可能是在浏览器中。主观上,在window中使用“name”在风格上与使用window.name来引用全局变量一致。将全局变量作为窗口的财产而不是变量进行访问,可以最大限度地减少代码中引用的未声明变量的数量(为了linting的好处),并避免全局变量被局部变量遮蔽的可能性。此外,如果全局对象使您的皮肤爬行,您可能会觉得仅用这根相对较长的棍子触摸它们更舒服。