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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

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

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

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

其他回答

测试未声明(未定义)变量的捷径是

if (typeof variable === "undefined") {
  ...
}

我发现它对于检测在浏览器外部运行的脚本(没有声明窗口变量)非常有用。

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

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

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

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

在许多情况下,使用:

if (elem) { // or !elem

会为你做这件事的!。。。这将检查以下情况:

undefined:如果值未定义且未定义null:如果它为null,例如,如果DOM元素不存在。。。空字符串:“”0:数字零NaN:不是数字假的

所以它将涵盖所有的情况,但我们也希望涵盖一些奇怪的情况,例如,一个带空格的字符串,比如这个“”,这将在javascript中定义,因为它在字符串中有空格。。。例如,在本例中,您使用trim()再添加一个检查,例如:

if(elem) {

if(typeof elem === 'string' && elem.trim()) {
///

此外,这些检查仅针对值,因为对象和数组在Javascript中的工作方式不同,所以空数组[]和空对象{}始终为true。

我创建了下面的图像,以显示答案的简要说明:

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

或者更好

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

适用于所有浏览器