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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

在问题中概述的特定情况下,

typeof window.console === "undefined"

与相同

window.console === undefined

我更喜欢后者,因为它更短。

请注意,我们只在全局范围内查找控制台(这是所有浏览器中的窗口对象)。在这种特殊情况下,这是可取的。我们不希望在其他地方定义控制台。

@BrianKelley在他出色的回答中解释了技术细节。我只是补充了不足的结论,并将其消化为更容易阅读的内容。

其他回答

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

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

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

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

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

这取决于情况。如果您正在检查代码之外可能或可能尚未全局定义的内容(例如jQuery),您需要:

if (typeof(jQuery) != "undefined")

(这里不需要严格相等,typeof总是返回字符串。)但是,如果函数的参数可能已传递,也可能未传递,则它们将始终被定义,但如果忽略,则为null。

function sayHello(name) {
    if (name) return "Hello, " + name;
    else return "Hello unknown person";
}
sayHello(); // => "Hello unknown person"

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

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。