Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/43.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按名称作为字符串检查局部范围内是否存在变量?_Javascript - Fatal编程技术网

Javascript 按名称作为字符串检查局部范围内是否存在变量?

Javascript 按名称作为字符串检查局部范围内是否存在变量?,javascript,Javascript,我想知道是否有一个变量存在于局部作用域中,其给定名称为字符串。有没有办法做到这一点 var name = 'myVariable'; function test(myVariable) { //CHECK HERE if there is a locally scoped variable with the same name //as the value of 'name' } 尽管有一些特殊情况(比如一个实际命名为“undefined”的变量)存在 (或者我可能

我想知道是否有一个变量存在于局部作用域中,其给定名称为字符串。有没有办法做到这一点

var name = 'myVariable';

function test(myVariable) {

     //CHECK HERE if there is a locally scoped variable with the same name
     //as the value of 'name' 

}
尽管有一些特殊情况(比如一个实际命名为“undefined”的变量)存在


(或者我可能完全不明白你的意思……)

我将借助班德拉米的回答和我的评论,因为我相信这是完成你所要做的事情的唯一途径。是的,我知道我正在使用
eval
,但我不相信有任何选择

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

我认为这是不可能的(假设您打算像检查全局变量一样检查
window[myVariable]
),除非有某种方法可以应用名称空间,也许?然而,我想说的是错误的。实际的用例是什么?它需要跨浏览器工作吗?如果变量存在于全局(或任何更高级别)范围内,我认为typeof不会返回undefined,如果我没有弄错的话?是的,如果变量在全局范围内,它将返回true,您可以将其改为:
if(typeof eval(name)!='undefined'&&typeof window[name]='undefined'){//在此范围内存在}
@echochamber Danke.:)谢谢Brandami。这很酷,但我认为它做得不太好。如果这个函数在另一个函数中,它会在闭包中拾取变量。此外,如果局部和全局存在同名变量…@Teemu你已经说过3次了,现在请解释为什么它没有意义。
if (typeof eval(name) !== 'undefined' && typeof window[name] === 'undefined'){ 
   // variable exists in this scope 
}