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

其他回答

您也可以使用!!在变量之前检查它是否已定义。例如。

let dog = "woof";
let chineseCat; // Undefined.
console.log("1.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");

chineseCat= "mao"; // dog and chineseCat are now defined.
console.log("2.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");

输出:

1.
Both are NOT defined
2. 
Both are defined
if (variable === undefined) {}

工作正常,只检查未定义。

尝试捕捉

如果根本没有定义变量(例如:定义全局变量的外部库尚未加载-例如谷歌地图),您可以使用try-catch块检查这一点,无需中断代码执行,如下所示(不需要使用严格模式)

尝试{未定义变量;}捕获(e){console.log('检测到:变量不存在');}console.log('但代码仍在执行');未定义变量;//没有try-catch包装器代码在此处停止console.log('代码执行停止。您不会在控制台上看到此消息');

奖金:(参考其他答案)为什么==比==更清楚(来源)

如果(a==b)

如果(a===b)

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

以下是使用此['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 (typeof variable !== 'undefined') {
    // the variable is defined
}