Home  >  Article  >  Web Front-end  >  js code to determine whether a variable is undefined_javascript skills

js code to determine whether a variable is undefined_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:48:401433browse

For example:

if(!myVar01)alert("An error occurred");

// An exception occurs directly in this code because the variable myVar01 is not declared if("undefined" == typeof myVar01)alert("An error occurred");

//Writing like this will prevent exceptions

And: var myVar01; if(undefined == myVar01)alert("An error occurred");

// This code will run correctly if("undefined" == typeof myVar01)alert("An error occurred");

// This code will also run correctly

Conclusion: We use the following method to ensure foolproof if("undefined" == typeof myVar01)alert("An error occurred");

// This code will also run correctly

Of course, judging the validity of data is far more than just that, there is also the judgment of null, whether the number is out of bounds.

Practical application:
We do not define some pages of downlm, but if some pages are defined, such a judgment method may be needed. If it is not defined, it will not be executed.

if("undefined" != typeof downlm){ 
if(downlm=="soft"){ 
document.write('成功'); 
} 
}

Tested perfect.

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