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

if (elem) { // or !elem

or

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

or

if (elem != null) {

当前回答

你可以试试。。。捕获块如下所示:

var status='变量存在'尝试{我的变量}catch(ReferenceError){status='变量不存在'}console.log(状态)

缺点是不能将其放在函数中,因为它会引发ReferenceError

函数变量Exists(x){var状态=真尝试{x(x)}catch(ReferenceError){状态=假}返回状态}console.log(variableExists(x))

编辑:

如果您在前端Javascript中工作,需要检查变量是否未初始化(var x=undefined将算作未初始化),可以使用:

函数globalVariableExists(变量){if(window[variable]!=未定义){返回true}return false}var x=未定义console.log(globalVariableExists(“x”))console.log(globalVariableExists(“y”))变量z=123console.log(globalVariableExists(“z”))

编辑2:

如果需要检查当前作用域中是否存在变量,只需将其与字符串中包含的变量名称一起传递给函数即可:

函数variableExists(变量,thisObj){if(thisObj[variable]!==未定义){返回true}return false}类someClass{构造函数(名称){这个.x=99这个。y=99这个.z=99这个。v=99console.log(variableExists(name,this))}}新建someClass('x')新建someClass('y')新建someClass('z')新建someClass('v')新建someClass('doesNotExist')

其他回答

这取决于您是否只关心变量是否已定义,或者是否希望它具有有意义的值。

检查类型是否未定义将检查变量是否已定义。

==空或!==null将仅检查变量的值是否完全为null。

==空或!=null将检查该值是否未定义或为null。

if(value)将检查变量是否为undefined、null、0或空字符串。

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

以下是使用此['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!
if (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");
}