Use try catch to determine whether a variable is declared undeclared or unassigned

  • 2020-03-30 02:19:44
  • OfStack

The purpose is that if a variable is declared unassigned, it can be assigned directly; And you cannot change the scope of a variable

If it's not declared, declare it again,

If (typeof(a)=='undefined'){var a='ss'; },

However, this method returns true for undeclared or declared unassigned variables. And if so:
 
var a; 
function f(){ 
if(typeof(a)=='undefined') 
{var a=1;} 
} 
f(); 
console.log(a); 

Undefined, because f() is just declaring a local variable with the same name.

If (noValueV==null) returns true; if(noValueV==null) returns true.

Undeclared variable :if(noDeclareV==null), an error is reported.

So you can do this:
 
function f( ){ 
if(typeof(v)=='undefined'){ 
try{ 
if(v==null)//Indicates that v is declared unassigned
v=1; //If v is a global variable, this does not change its scope
} 
catch(err){//So v is undeclared
var v;v=2; 
} 
} 
console.log(v); 
} 
f( ); 

This is also incorrect, because js has the 'declare ahead' feature, which means that variables declared in a function are visible in this function and in its children, regardless of where they are declared in the function.

So because of the var v up here; In either case, only try is used.

Revise it:
 
function f( ){ 
if(typeof(v)=='undefined'){ 
try{ 
if(v==null)//Indicates that v is declared unassigned
v=1; //If v is a global variable, this does not change its scope
} 
catch(err){//So v is undeclared
eval('var v');v=2; //It's different here
} 
} 
console.log(v); 
} 
f( ); 

That's it.

Write it as a judgment function that returns 'noDeclare' to indicate that the variable is undeclared, 'noValue' to indicate that the variable has been declared unassigned, and 'hasValue' to indicate that the variable has been declared and assigned:
 
function f(v){ 
if(typeof(v)=='undefined'){ 
try{ 
if(v==null) 
return 'noValue'; 
} 
catch(err){ 
return 'noDeclare'; 
} 
} 
else return 'hasValue'; 
} 
var a; 
console.log(f(a)); 
a=0; 
console.log(f(a)); 
console.log(f(b)); 

Wrong again... The console. The log (f (b)); An error is reported...

Related articles: