Home  >  Article  >  Web Front-end  >  Methods to determine null, undefined and NaN in JS_jquery

Methods to determine null, undefined and NaN in JS_jquery

WBOY
WBOYOriginal
2016-05-16 16:54:141169browse

I wrote str ="s" ;

and then Nan appeared and I searched for a while.

Collect the data and judge as follows:

1. Judge undefined:

Copy 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 results obtained by the comparison are all 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:

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


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: This is usually enough if you don’t need to differentiate.
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