如何检查javascript中是否存在变量? [英] how to check if a variable exist in javascript?
本文介绍了如何检查javascript中是否存在变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不是在询问变量是否未定义或是否为 null
。我想检查变量是否存在。这可能吗?
I am not asking if the variable is undefined or if it is null
. I want to check if the variable exists or not. Is this possible?
推荐答案
typeof
技术不起作用,因为它们没有区分何时根本没有声明变量,何时声明变量但未赋值,或声明并设置等于undefined。
The typeof
techniques don't work because they don't distinguish between when a variable has not been declared at all and when a variable has been declared but not assigned a value, or declared and set equal to undefined.
但是如果你尝试使用未在if条件中声明的变量(或在赋值的右侧),您会收到错误。所以这应该有效:
But if you try to use a variable that hasn't been declared in an if condition (or on the right-hand side of an assignment) you get an error. So this should work:
var exists = true;
try {
if (someVar)
exists = true;
} catch(e) { exists = false; }
if (exists)
// do something - exists only == true if someVar has been declared somewhere.
这篇关于如何检查javascript中是否存在变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文