This article describes how to use try-catch to determine whether a variable has been declared and not assigned a value or not. If a variable has been declared and not assigned a value, the value can be assigned directly, and the scope of the variable cannot be changed.
If it is not stated, redeclare it,
The common method for searching on the internet is if (typeof (a) = 'undefined') {var a = 'ss ';},
However, this method returns true for variables that are not declared or are not assigned a value. And if so:
The Code is as follows:
Var;
Function f (){
If (typeof (a) = 'undefined ')
{Var a = 1 ;}
}
F ();
Console. log ();
Undefined is displayed, because f () only declares a local variable with the same name.
However, if the variable is declared as if (noValueV = null), true is returned;
If (noDeclareV = null), an error is returned.
So we can do this:
The Code is as follows:
Function f (){
If (typeof (v) = 'undefined '){
Try {
If (v = null) // note that v is declared not assigned a value
V = 1; // If v is a global variable, it will not change its scope.
}
Catch (err) {// note that v is not declared
Var v; v = 2;
}
}
Console. log (v );
}
F ();
This is also not true, because js has the 'advance declaration 'feature, that is, the variables declared in the function are visible in this function and the sub-functions of this function, no matter where it is declared in the function.
Therefore, because of the var v; in the above case, only try is used.
Modify:
The Code is as follows:
Function f (){
If (typeof (v) = 'undefined '){
Try {
If (v = null) // note that v is declared not assigned a value
V = 1; // If v is a global variable, it will not change its scope.
}
Catch (err) {// note that v is not declared
Eval ('var V'); v = 2; // different here
}
}
Console. log (v );
}
F ();
In this way, you can.
Write a judgment function and return 'nodeclare' to indicate that the variable is not declared, 'novalue' to indicate that the variable has been declared and not assigned a value, and 'hasvalue' to indicate that the variable has been declared and assigned a value:
The Code is as follows:
Function f (v ){
If (typeof (v) = 'undefined '){
Try {
If (v = null)
Return 'novalue ';
}
Catch (err ){
Return 'nodeclare ';
}
}
Else return 'hasvalue ';
}
Var;
Console. log (f ());
A = 0;
Console. log (f ());
Console. log (f (B ));
Another error occurs... console. log (f (B ......