通过字符串形式的名称检查变量是否存在于本地作用域内

Check if a variable exists within local scope by name as string?

本文关键字:是否 变量 存在 于本地 作用域 检查 字符串      更新时间:2024-04-05

我想知道本地作用域中是否存在一个以字符串形式命名的变量。有办法做这样的事情吗?:

var name = 'myVariable';
function test(myVariable) {
     //CHECK HERE if there is a locally scoped variable with the same name
     //as the value of 'name' 
}

我将借鉴Bandrami的回答和我的评论,因为我相信这是完成您想要做的事情的唯一方法。是的,我知道我使用的是eval,但我不认为有任何选择。

if (typeof eval(name) !== 'undefined' && typeof window[name] === 'undefined'){ 
   // variable exists in this scope 
}
if (typeof eval(name) === 'undefined')

尽管那里有一些角落的情况(比如一个实际上名为"undefined"的变量)。。。

(或者我可能完全没有理解你的观点…)