Js之判断null、undefined与NaN的方法

目录

1.判断undefined

2.判断null

3.判断NaN

4.判断undefined和null

5.判断undefined、null与NaN


1.判断undefined

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

undefined类型只有一个值,即undefined。当声明的变量还未被初始化时变量的默认值为undefined

var oValue;  
alert(oValue == undefined); //output "true"  没有初始化,默认为undefined


typeof (undefined) ;//undefined ;说明他是undefined类型


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

2.判断null

null类型也只有一个值,即null。null用来表示尚未存在的对象,常用来表示函数企图返回一个不存在的对象

//当页面上不存在id为"notExistElement"的DOM节点时,这段代码显示为"true",因为我们尝试获取一个不存在的对象
alert(null == document.getElementById('notExistElement');

typeof (null) ;//Object ; 说明他是一个特殊的对象。

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

3.判断NaN

 NaN 与任何值(包括其自身)相比得到的结果均是 false,所以要判断某个值是否是 NaN,不能使用 == 或 === 运算符

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

4.判断undefined和null

ECMAScript认为undefined是从null派生出来的,所以把它们定义为相等的。null == undefined

alert(null == undefined); //output "true"  

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

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

5.判断undefined、null与NaN

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

猜你喜欢

转载自blog.csdn.net/mmake1994/article/details/87989787