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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

我更喜欢这种方法,因为它的准确性和简洁性:

变量x如果(x===无效0){console.log(“x未定义”)}其他{console.log(“x已定义”)}

正如在其他评论和回答中提到的,undefined不能保证是undefineed。因为它不是关键字,所以可以在全局范围以外的范围中将其重新定义为变量。这里有一个小例子可以说明这种细微差别:

var undefined='bar'console.log(`在全局范围内:${undefined}`)函数foo(){var undefined=“已定义”变量x如果(x===未定义){console.log(`x===undefined`)}其他{console.log(`x!==undefined`)}如果(x===无效0){console.log(`x===void 0`)}其他{console.log(`x!==void 0`)}}foo()

请参阅void以了解兼容性(IE5支持!?!!哇!)。

其他回答

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==)?

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

或者更好

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

适用于所有浏览器

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

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

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

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

当您执行简单的作业和相关检查时,还有另一种简便的方法来检查这一点。只需使用条件(三元)运算符。

var values = typeof variable !== 'undefined' ? variable : '';

当您尝试使用引用变量的实例赋值来声明全局变量时,这也会很有用。

若你们想检查变量不应该是未定义的或空的。然后执行以下检查。

当声明变量时,如果您想检查值,这甚至很简单:它将同时执行未定义和空检查。

var values = variable ? variable : '';