how to check if a variable exist in javascript?
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?
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.
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.
if ('bob' in window) console.log(bob);
请记住,即使你用var
声明了一个变量,这也意味着它存在。
I use this function:
function exists(varname){
try {
var x = eval(varname);
return true;
} catch(e) { return false; }
}
Hope this helps.
链接地址: http://www.djcxy.com/p/19448.html上一篇: 一个变量是否是未定义的