如何在 JavaScript 中检查"is not defined" eval(var)?



有很多信息需要检查" undefined"JavaScript中的普通变量,但我需要检查eval(var),如:

var Hello_0 = "Hello 0 !";
console.log(" Hello_0 is: " + eval("Hello_"+0));
var dinamyc_var = "Hello_"+1;
//None of the next conditionals is triggered///
if (eval(dinamyc_var) === undefined) {
console.log(" dinamyc_var is undefined ");
} 
if (eval(dinamyc_var) === null) {
console.log(" dinamyc_var is null ");
}
if ( typeof eval(created_node) === undefined ) {
console.log(" dinamyc_var is typeof undefined ");
}
if ( typeof eval(created_node) === null ) {
console.log(" dinamyc_var is typeof null ");
}
console.log(" dinamyc_var is: " + eval(dinamyc_var));

https://jsfiddle.net/mczdrv5t/

控制台显示eval("Hello_"+0)的值,因为已声明,但是当尝试调用eval("Hello_"+1)时,控制台显示下一个错误,因为没有声明。我需要处理可能未声明的变量。

Uncaught ReferenceError: Hello_1 is not definedat eval (eval at ....)

不要使用eval.如果需要存储不同名称的值,请使用对象:

const values = {}
values["Hello_0"] = "Hello 0 !"
if (values["Hello_" + 1] === undefined) {
// ...
}

作为旁注,if (eval('typeof ' + dynamic_var) === 'undefined')可以工作,但不要使用eval。

也不要使用window[dynamic_var] = ...来存储全局变量,这些名称可能与现有的全局变量冲突。

最新更新