Home >Web Front-end >JS Tutorial >Use try-catch to determine whether a variable has been declared, undeclared or unassigned_javascript skills

Use try-catch to determine whether a variable has been declared, undeclared or unassigned_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:55:391136browse

The purpose is that if a variable has been declared but not assigned, it can be assigned a value directly; and the scope of the variable cannot be changed

If it is not declared, re-declare it.

I searched on the Internet, A common method is if(typeof(a)=='undefined'){var a='ss';},

But this method will return true for undeclared or declared unassigned variables. And if so:

Copy the code The code is as follows:

var a;
function f(){
if(typeof(a)=='undefined')
{var a=1;}
}
f();
console.log(a);

will display undefined because f() only declares a local variable with the same name.

But if it is a declared unassigned variable: if (noValueV==null), it will return true;

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

So it works like this:
Copy the code The code is as follows:

function f ( ){
if(typeof(v)=='undefined'){
try{
if(v==null)//Indicate that v is declared but not assigned
v=1; //If v is a global variable, this will not change its scope
}
catch(err){//Indicate that v is undeclared
var v;v=2;
}
}
console.log(v);
}
f( );

This is also wrong, because js has the feature of 'declaration in advance', that is, functions Variables declared within a function are visible in this function and in subfunctions of this function, regardless of where it is declared within the function.

So due to the var v; above, no matter what the situation, only try is used.

Modify it:
Copy the code The code is as follows:

function f( ){
if(typeof(v)=='undefined'){
try{
if(v==null)//Indicate that v is declared but not assigned
v=1; / /If v is a global variable, this will not change its scope
}
catch(err){//Indicate that v is undeclared
eval('var v');v=2; / /It’s different here
}
}
console.log(v);
}
f( );

That’s it.

is written as a judgment function, returning 'noDeclare' means the variable has not been declared, 'noValue' means the variable has been declared but has not been assigned a value, and 'hasValue' means the variable has been declared and assigned a value:
Copy code 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 a;
console.log(f(a));
a=0;
console.log(f(a) ));
console.log(f(b));

Wrong again... console.log(f(b)); will report an error... ...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn