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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

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

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

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

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

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

var values = variable ? variable : '';

其他回答

如何检查变量是否存在

这是一个非常可靠的解决方案,用于测试变量是否存在并已初始化:

var setOrNot = typeof variable !== typeof undefined;

它最常用于与三元运算符结合使用,以在某个变量尚未初始化的情况下设置默认值:

var dark = typeof darkColor !== typeof undefined ? darkColor : "black";

封装问题

不幸的是,您不能简单地将检查封装在函数中。

你可能会想到这样做:

function isset(variable) {
    return typeof variable !== typeof undefined;
}

然而,如果您正在调用例如isset(foo),并且尚未定义变量foo,这将产生引用错误,因为您无法将不存在的变量传递给函数:

未捕获引用错误:未定义foo


测试函数参数是否未定义

虽然我们的isset函数不能用于测试变量是否存在(原因如上所述),但它确实允许我们测试函数的参数是否未定义:

var a = '5';

var test = function(x, y) {
    console.log(isset(x));
    console.log(isset(y));
};

test(a);

// OUTPUT :
// ------------
// TRUE
// FALSE

即使没有将y的值传递给函数测试,我们的isset函数在这种情况下也能很好地工作,因为在函数测试中y是一个未定义的值。

最稳健的“是定义的”检查是使用类型

if (typeof elem === 'undefined')

如果您只是检查一个定义的变量来分配一个默认值您可以经常这样做:

elem = elem || defaultElem;

它通常很好用,请参见:在javascript中设置默认值的惯用方法

还有一行使用typeof关键字:

elem = (typeof elem === 'undefined') ? defaultElem : elem;

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

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

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

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

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