找出变量是否存在 [英] Find out if a Variable exists
问题描述
我想找出一个Javascript变量是否存在.到目前为止,这是我在不同论坛上共同总结的内容:
I would like to find out if a Javascript variable exists. This is what I have so far which was cobbled together from different forums:
function valueOfVar(foo){
var has_foo = typeof foo != 'undefined';
if(has_foo){
alert('1 = true');
return true;
}
else {
alert('1 = false');
return false;
}
}
请注意,我希望传递一个 字符串为foo.示例:valueOfVar(box_split [0] +'_ 2')
Please note, I wish to pass in a string as foo. Example: valueOfVar(box_split[0]+'_2')
现在,我不认为这可行,因为当某些变量甚至不存在时,它会返回true.实际上,它似乎一直都返回true.
Now, I don't think this works because it returns true when certain variables don't even exist. In fact, it seems to return true all the time.
一个有效的JQuery实现也很不错.
A JQuery implementation that works would also be great as I make use of this.
感谢所有帮助
推荐答案
您的意思是这样的吗?
function variableDefined (name) {
return typeof this[name] !== 'undefined';
}
console.log(variableDefined('fred'));
// Logs "false"
var fred = 10;
console.log(variableDefined('fred'));
// Logs "true"
如果您希望能够处理局部变量,则必须做一些很奇怪的事情,像这样:
If you want to be able to handle local variables you'll have to do something quite weird like this:
function variableDefined2 (value) {
return typeof value !== 'undefined';
}
function test() {
var name = 'alice'
console.log(variableDefined2(eval(name)));
var alice = 11;
console.log(variableDefined2(eval(name)));
}
test();
// Logs false, true
这篇关于找出变量是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!