JS中判断null、undefined与NaN的方法

1.判断undefined:函数

var  tmp = undefined;
if  ( typeof (tmp) ==  "undefined" ){ 
console.log( "undefined" );
}

说明:typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined" code

2.判断null:字符串

var  tmp =  null ;
if  (!tmp &&  typeof (tmp)!= "undefined"  && tmp!=0){ 
console.log( "null" );
}
3.判断NaN:
var  tmp = 0/0;
if (isNaN(tmp)){
console.log( "NaN" );
}
说明:若是把 NaN 与任何值(包括其自身)相比获得的结果均是 false,因此要判断某个值是不是 NaN,不能使用 == 或 === 运算符。
提示:isNaN() 函数一般用于检测 parseFloat() 和 parseInt() 的结果,以判断它们表示的是不是合法的数字。固然也能够用 isNaN() 函数来检测算数错误,好比用 0 做除数的状况。 
4.判断undefined和null的关系:

var tmp = undefined;
if (tmp == undefined) {
console.log("undefined == undefined");
}string

var tmp = undefined;
if (tmp == null) {
console.log("null == undefined");
}io

结论:null == undefined console

5.判断undefined、null与NaN:function

var tmp = null;
var tmp1 = undefined;
var tmp2 = NaN;
if (!tmp) {
console.log("null or undefined or NaN");
}
if (!tmp1) {
console.log("null or undefined or NaN");
}
if (!tmp2) {
console.log("null or undefined or NaN");
}class

结果:都打印object

相关文章
相关标签/搜索