Home > Web Front-end > JS Tutorial > Methods to determine null, undefined and NaN in JS_javascript skills

Methods to determine null, undefined and NaN in JS_javascript skills

WBOY
Release: 2016-05-16 16:54:36
Original
1354 people have browsed it

I wrote str ="s" ;
Then Nan appeared and I searched for it for a while.
Collect the information and judge as follows:
1. Judge undefined:

Copy the code The code is as follows:

var tmp = undefined;
if (typeof(tmp) == "undefined"){
alert("undefined");
}


Explanation: typeof returns a string, there are six possibilities: "number", "string", "boolean", "object", "function ", "undefined"
2. Determine null:
Copy code The code is as follows:

var tmp = null;
if (!tmp && typeof(tmp)!="undefined" && tmp!=0){
alert( "null");
} 


3. Determine NaN:
Copy code The code is as follows:

var tmp = 0/0;
if(isNaN(tmp)){
alert("NaN");
}


Explanation: If NaN is compared with any value (including itself), the result will be false, so To determine whether a value is NaN, you cannot use the == or === operators.
Tip: The isNaN() function is usually used to detect the results of parseFloat() and parseInt() to determine whether they represent legal numbers. Of course, you can also use the isNaN() function to detect arithmetic errors, such as using 0 as a divisor.
4. Judge undefined and null:
Copy code The code is as follows:

< span style="font-size: small;">var tmp = undefined;
if (tmp== undefined)
{
alert("null or undefined");
} < /span>

Copy code The code is as follows:

var tmp = undefined;
if (tmp== null)
{
alert("null or undefined");
}

Explanation: null==undefined

5. Judge undefined, null and NaN:
Copy code The code is as follows:

var tmp = null;
if (!tmp)
{
alert("null or undefined or NaN");
}


Tip: Generally not so distinguishable Just use this.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template