Home > Article > Web Front-end > js code to determine whether a variable is undefined_javascript skills
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.