Home >Web Front-end >JS Tutorial >In-depth understanding of variables and scope, undefined and null_javascript skills in JS

In-depth understanding of variables and scope, undefined and null_javascript skills in JS

WBOY
WBOYOriginal
2016-05-16 16:57:151184browse

Situation One

Copy code The code is as follows:

< ;script>
 var i; //Global variable
 //The method name is camel nomenclature
 //The variables in the method are local variables

 function sayHello(){
 var x=100;
 alert(x);
 x ;
 }
 sayHello(); //output 100
 alert(x ); //Error is reported because x is a local variable and cannot be accessed


Situation Two
Copy code The code is as follows:

<script><br>function sayHello(){<br> var x=100;<br> if(x==100){<br> var y=x 1;<br> alert(y); //output 101<br>}<br> alert(y); //also output 101, in the method Internally, there is no block-level scope, not in C#! ! ! <p> for(var i=0;i<2;i ){<br>  alert(i)<br> } //The variables defined in the for loop are block-level scope <br> alert(i); //Because i is a local variable, output 2</p> <p>}<br>sayHello();<br></script>


Note: Variables do not need to be declared with var before use. Such variables will be considered "global variables". But it’s rarely used like this

About undefined and null

In the following situations, the value of the variable is undefined
1. The variable is defined but no value is assigned, then the value of the variable is undefined
2. The called method has no return value, and the returned value is undefined
3. If the attribute value of the object does not exist, the return value is undefined, such as: document.ddd

Example1:

Copy code The code is as follows:

var xx;
var yy=null;

if(xx==yy){

alert('equal');

}

else{

 alert('not equal');
}


The output result is equal, because when making if judgment, the browser will judge the value of xx and yy, because the two None of them have specific values, and they are considered false.
If the if judgment is replaced with ===[all equals sign], the output will not be equal! Because === means that the data types and values ​​of xx and yy must be the same!

Example2:
Copy code The code is as follows:

var xx=10
var yy='10';

if(xx==yy){

alert('equal');
}

else{

 alert('not equal');
}


The output is equal. If it is changed to ===, the output is not equal

Example3:

Copy code The code is as follows:

var n='10';
switch(n){
 case 10:

 alert('number');
break;

case '10':

 alert('string');
 break;
}


Output String
The judgment in switch should consider the type

Summary: The judgment in if is to judge the value, regardless of the type

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
Previous article:Seajs study notes_SeajsNext article:Seajs study notes_Seajs