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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

最稳健的“是定义的”检查是使用类型

if (typeof elem === 'undefined')

如果您只是检查一个定义的变量来分配一个默认值您可以经常这样做:

elem = elem || defaultElem;

它通常很好用,请参见:在javascript中设置默认值的惯用方法

还有一行使用typeof关键字:

elem = (typeof elem === 'undefined') ? defaultElem : elem;

其他回答

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

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

在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的好处),并避免全局变量被局部变量遮蔽的可能性。此外,如果全局对象使您的皮肤爬行,您可能会觉得仅用这根相对较长的棍子触摸它们更舒服。

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

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

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

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

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

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

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

..可以简化为:

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

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

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

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