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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

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

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

其他回答

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


var _undefined;
var _null = null;

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

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

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

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

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

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

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

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

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

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