if (typeof v === "undefined") {// no variable "v" is defined in the current scope// *or* some variable v exists and has been assigned the value undefined} else {// some variable (global or local) "v" is defined in the current scope// *and* it contains a value other than undefined}
if ("v" in window) {// global variable v is defined} else {// global variable v is not defined}
当然,这是假设你在浏览器中运行(其中window是全局对象的名称)。但是如果你像这样摆弄全局变量,你可能在浏览器中。主观上,使用'name' in window与使用window.name引用全局变量在风格上是一致的。将全局变量作为window的属性而不是变量访问,可以让你最大限度地减少代码中引用的未声明变量的数量(为了lint的好处),并避免全局变量被局部变量遮蔽的可能性。此外,如果全局变量让你毛骨悚然,你可能会觉得只有用这根相对较长的棍子触摸它们更舒服。
"use strict";
// var someVar;
var declared;try {someVar;declared = true;} catch(e) {declared = false;}
if (declared) {console.log("someVar is declared; now has the value: " + someVar);} else {console.log("someVar is not declared");}
if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy valueif (this['elem'] !== undefined) {...}; // check if it's been declaredif (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
// these will work even if you have an improper variable definition declared hereelem = null; // <-- no var here!! BAD!
try{notDefinedVariable;} catch(e) {console.log('detected: variable not exists');}
console.log('but the code is still executed');
notDefinedVariable; // without try-catch wrapper code stops here
console.log('code execution stops. You will NOT see this message on console');
var status = 'Variable exists'
try {myVar} catch (ReferenceError) {status = 'Variable does not exist'}
console.log(status)
缺点是你不能把它放在一个函数中,因为它会抛出一个引用错误
function variableExists(x) {var status = truetry {x} catch (ReferenceError) {status = false}
return status}
console.log(variableExists(x))
编辑:
如果您使用前端Javascript并且需要检查变量是否未初始化(var x = undefined将算作未初始化),您可以使用:
function globalVariableExists(variable) {if (window[variable] != undefined) {return true}
return false}
var x = undefined
console.log(globalVariableExists("x"))
console.log(globalVariableExists("y"))
var z = 123
console.log(globalVariableExists("z"))
let dog = "woof";let chineseCat; // Undefined.console.log("1.");console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
chineseCat= "mao"; // dog and chineseCat are now defined.console.log("2.");console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");