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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

我根据对象使用两种不同的方式。

if( !variable ){
  // variable is either
  // 1. '';
  // 2. 0;
  // 3. undefined;
  // 4. null;
  // 5. false;
}

有时我不想将空字符串求值为false,所以我使用这种情况

function invalid( item ){
  return (item === undefined || item === null);
}

if( invalid( variable )){
  // only here if null or undefined;
}

如果你需要相反的东西,那么首先!变量变为!!变量,并且在无效函数中==变为!=函数名变为notInvalid。

其他回答

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

我根据对象使用两种不同的方式。

if( !variable ){
  // variable is either
  // 1. '';
  // 2. 0;
  // 3. undefined;
  // 4. null;
  // 5. false;
}

有时我不想将空字符串求值为false,所以我使用这种情况

function invalid( item ){
  return (item === undefined || item === null);
}

if( invalid( variable )){
  // only here if null or undefined;
}

如果你需要相反的东西,那么首先!变量变为!!变量,并且在无效函数中==变为!=函数名变为notInvalid。

这些答案(除了Fred Gandt解决方案)要么不正确,要么不完整。

假设我需要我的variableName;携带一个未定义的值,因此它是以var variableName等方式声明的;这意味着它已经初始化;-如何检查是否已申报?

或者更好——我如何立即检查“Book1.chapter22.paragraph37”是否存在一次调用,但不会引起引用错误?

我们通过使用最强大的JasvaScript运算符in运算符来实现

"[variable||property]" in [context||root] 
>> true||false

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

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

即使使用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");
}