哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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。

其他回答

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

typeof window.console === "undefined"

与相同

window.console === undefined

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

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

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

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

或者更好

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

适用于所有浏览器

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

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

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

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

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

var values = variable ? variable : '';

为了使if条件正确工作,我们必须使用关键字let来创建变量。

let name = undefined; 
if (name) { 
    alert('valid')
};

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

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