JavaScript detects if there are any problems with variables

  • 2020-03-27 00:00:10
  • OfStack

When writing JavaScript programs, you often need to detect the existence of a variable, which is a very simple task, but if you are not careful, you will encounter some problems. There are mainly some points:

1. Ordinary variables
 
<script type="text/javascript"> 
if(variable){ 
alert('rain man'); 
} 
</script> 

The 'variable is not defined' error occurs, and the expected dialog pops up if you change it to:
 
<script type="text/javascript"> 
if( typeof variable == 'undefined' ){ 
alert('rain man'); 
} 
</script> 

2. Properties of objects
 
<script type="text/javascript"> 
var two = {}; 
if(two.b){ 
alert('rain man'); 
} 
if( window.addEventListener ){ 
alert('This is not IE!'); 
} 
</script> 

Typeof is not required for properties of the detected object.

3. You run into a similar problem when you add properties to an object
 
<script type="text/javascript"> 
var obj = {}; 
obj.property.number = 2; //The 'obj.property is undefined' error will appear

 
var obj = {}; 
obj.property = 2 ; 
obj.property.number = 3; 
</script> 

Related articles: