When writing JavaScript programs, you often need to detect whether a certain variable exists. This is a very simple task, but if you are not careful, you will encounter some problems. There are some main points:
1. Ordinary variables
<script type="text/javascript">
if(variable){
alert('rain man');
}
</script>
At this time, an error of 'variable is not defined' will appear. If it is changed to the following, the expected dialog box will pop up:
<script type="text/javascript">
if( typeof variable == 'undefined' ){
alert('rain man');
}
</script>
2. Object properties
<script type="text/javascript">
var two = {};
if(){
alert('rain man');
}
if( ){
alert('This is not IE!');
}
</script>
For the properties of the detection object, you do not need to use typeof.
3. When adding attributes to objects, you will also encounter similar problems.
<script type="text/javascript">
var obj = {};
= 2; //The error ' is undefined' will appear at this time
/**
* Although there is no syntax error in the following situation, an error has actually occurred.
* Attributes are unique to compound variables, but numeric variables and cannot contain attributes.
*/
var obj = {};
= 2 ;
= 3;
</script>
1. Ordinary variables
Copy the codeThe code is as follows:
<script type="text/javascript">
if(variable){
alert('rain man');
}
</script>
At this time, an error of 'variable is not defined' will appear. If it is changed to the following, the expected dialog box will pop up:
Copy the codeThe code is as follows:
<script type="text/javascript">
if( typeof variable == 'undefined' ){
alert('rain man');
}
</script>
2. Object properties
Copy the codeThe code is as follows:
<script type="text/javascript">
var two = {};
if(){
alert('rain man');
}
if( ){
alert('This is not IE!');
}
</script>
For the properties of the detection object, you do not need to use typeof.
3. When adding attributes to objects, you will also encounter similar problems.
Copy the codeThe code is as follows:
<script type="text/javascript">
var obj = {};
= 2; //The error ' is undefined' will appear at this time
/**
* Although there is no syntax error in the following situation, an error has actually occurred.
* Attributes are unique to compound variables, but numeric variables and cannot contain attributes.
*/
var obj = {};
= 2 ;
= 3;
</script>