The idea is that if a variable is declared unassigned, it can be assigned directly, and the scope of the variable cannot be changed.
If it is not stated, it will be declared again,
Search on the Internet, the common method is if (typeof (a) = = ' undefined ') {var a= ' ss ';},
However, this method returns true for variables that are not declared or declared unassigned. And if that's the case:
Copy Code code as follows:
var A;
function f () {
if (typeof (a) = = ' undefined ')
{var a=1;}
}
f ();
Console.log (a);
The undefined is displayed because the F () only declares a local variable with the same name.
However, if the variable is declared unassigned: if (Novaluev==null), returns true;
Undeclared variable: if (nodeclarev==null), an error is issued.
So you can do this:
Copy Code code as follows:
function f () {
if (typeof (v) = = ' undefined ') {
try{
if (v==null)//Description V is declared unassigned
V=1; If V is a global variable, it does not change its scope
}
catch (Err) {//description V is not declared
var v;v=2;
}
}
Console.log (v);
}
f ();
This is also wrong, because JS has a ' Declaration of Advance ' feature, that is, variables declared within the function in this function and the function in the child functions are visible, regardless of where it is specifically in the function of where the declaration.
So because of the Var v above, it causes either of the cases to go only try.
Modify:
Copy Code code as follows:
function f () {
if (typeof (v) = = ' undefined ') {
try{
if (v==null)//Description V is declared unassigned
V=1; If V is a global variable, it does not change its scope
}
catch (Err) {//description V is not declared
Eval (' Var v '); v=2; It's not the same here.
}
}
Console.log (v);
}
f ();
That's it.
Write a judgment function that returns ' Nodeclare ' indicating that the variable is not declared, ' Novalue ' indicates that the variable has been declared unassigned, ' HasValue ' indicates that the variable has been declared assigned:
Copy Code code as follows:
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));
It's wrong again ... console.log (f (b)), and error ...