Js 判断对象 Undefined 和 Null

今天又去市场走了一下,吃了碗河南烩面,档面小,乱,脏,一想起以后就要过这种日子,很不是滋味在心头。

阿姨还没有请到,老板说要盖食堂。就中国人的效率来看,这敢情要等到世界杯开打。

买了四个apple,老板说7元,然后再从框子里随便拿了一下放进去。

天气冷,我也没说什么,出门在外,大家都不容易。

上火的,眼睛又发痒了,这对程序员来说不是一个好消息。

Js中判断一个对象是underfined 还是 Null一直还是比较重要的,先来看看Null:

var exp="";
if (exp.abc == null)//前提是必须存在exp这个对象,而对于它这个属性,则可进行判断,看是否为NUll
{
    alert("is null");
}
if(exp.abc==undefined)
{  
    alert("undefined");//exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 null 和 undefined 时可使用本法。
}

 

  

if(exp.ab()==null){  //这里是错的,会提示说没有这个ab()的方法,所以出错
    alert("function is null");
}
if(exp.ab()==undefined){  //这里也是错的
    alert("undefined");
}

 

if(!exp){ //当如果 exp 为 undefined,或字符体""、或null,或数字零,或 false,也会得到与 null 相同的结果,虽然 null 和二者不一样。注意:要同时判断 null、undefined、数字零、false 时可使用本法。
    alert("!exp");
}
exp=null;
console.log(typeof exp);//这里输出的一定是object,那么判断一个对象是否为Null?

if (!exp && typeof exp != "undefined" && exp != 0)
{
    alert("it is null");//就是这样子,但请记住,""  相当于 0 ,false 也相当于 0
}
//更简单的正确的方法:
var exp = null;
if (exp === null)
{
    alert("is null");
}

现在来看看Undefined 的判断:

if (a == undefined){
    alert("a is undefined");//出错:a is not defined
}

if (typeof(a) == "undefined") { //这样子写才是正确的!typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined"
   alert("a is undefined"); 
}

var tmp = undefined;  
if (tmp== undefined)  //undefined也是一种类型
{  
    alert("undefined");  
}

var tmp = null;  
if (tmp== undefined)  //null虽然不等于undefined,但他们之前可以相互判断
{  
    alert("undefined");  
}
if(tmp === undefined){  
    alert("null is equal undefined");
}else{  
    alert("null is not equal undefined");//事实证明 null 与 undefined 不是一样的
}

顺便加上一个判断数字的!

var tmp = 0/0;  
if(isNaN(tmp)){  
    alert("NaN");  
}
// 说明:如果把 NaN 与任何值(包括其自身)相比得到的结果均是 false,所以要判断某个值是否是 NaN,不能使用 == 或 === 运算符。
// 提示:isNaN() 函数通常用于检测 parseFloat() 和 parseInt() 的结果,以判断它们表示的是否是合法的数字。当然也可以用 isNaN() 函数来检测算数错误,比如用 0 作除数的情况。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值