The purpose is that if a variable is declared unassigned, it can be assigned directly; and the scope of the variable cannot be changed.
If not declared, redeclare it.
I searched online and found that the common method is if(typeof(a)=='undefined'){var a='ss';},
However, this method will return true for undeclared or unassigned variables. And if so:
The code copy is as follows:
var a;
function f(){
if(typeof(a)=='undefined')
{var a=1;}
}
f();
console.log(a);
Undefined will be displayed because f() just declares a local variable with the same name.
However, if it is a variable that has been declared unassigned: if(noValueV==null), it will return true;
Undeclared variable: if(noDeclareV==null), an error will be reported.
So it can be:
The code copy is as follows:
function f( ){
if(typeof(v)=='undefined'){
try{
if(v==null)//Indicate that v is declared unassigned
v=1; //If v is a global variable, it will not change its scope
}
catch(err){//Indicate that v is not declared
var v;v=2;
}
}
console.log(v);
}
f( );
This is also wrong, because js has the characteristic of 'declaring advance', that is, the variables declared in the function are visible in this function and in the subfunction of this function, no matter where it is declared in the function.
So due to the above var v;, in any case, you only try.
Modify it:
The code copy is as follows:
function f( ){
if(typeof(v)=='undefined'){
try{
if(v==null)//Indicate that v is declared unassigned
v=1; //If v is a global variable, it will not change its scope
}
catch(err){//Indicate that v is not declared
eval('var v');v=2; //It's different here
}
}
console.log(v);
}
f( );
That's all.
Written as a judgment function, returning 'noDeclare' means that the variable is not declared, 'noValue' means that the variable has been declared unassigned, and 'hasValue' means that the variable has been declared assigned:
The code copy is 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..... There will be an error when console.log(f(b));...