A-A+

js判断是否为null程序实现代码

2016年10月14日 前端设计 暂无评论 阅读 5 views 次

本文章来给大家介绍在js中一个特殊的类型null,有搞不清楚null是怎么用与怎么判断的朋友可参考本文章。

以下是不正确的用法,代码如下:

  1. var exp = null;  
  2. if (exp == null)  
  3. {  
  4.     alert("is null");  
  5. }  

exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 null 和 undefined 时可使用本法,代码如下:

  1. var exp = null;  
  2. if (!exp)  
  3. {  
  4.     alert("is null");  
  5. }  

如果 exp 为 undefined 或者数字零,也会得到与 null 相同的结果,虽然 null 和二者不一样。注意:要同时判断 null、undefined 和数字零时可使用本法,代码如下:

  1. var exp = null;  
  2. if (typeof(exp) == "null")  
  3. {  
  4.     alert("is null");  
  5. }  

为了向下兼容,exp 为 null 时,typeof 总返回 object,代码如下:

  1. var exp = null;  
  2. if (isNull(exp))  
  3. {  
  4.     alert("is null");  
  5. }  

JavaScript 中没有 isNull 这个函数。

以下是正确的用法,代码如下:

  1. var exp = null;  
  2. if (!exp && typeof(exp)!="undefined" && exp!=0)  
  3. {  //xiariboke.net  
  4.     alert("is null");  
  5. }   
  6.   
  7. //或  
  8.   
  9. var tmp = null;  
  10. if (!tmp && typeof(tmp)!="undefined" && tmp!=0){  
  11.     alert("null");  
  12.   
  13. }  

尽管如此,我们在 DOM 应用中,一般只需要用 (!exp) 来判断就可以了,因为 DOM 应用中,可能返回 null,可能返回 undefined,如果具体判断 null 还是 undefined 会使程序过于复杂.

要同时判断 null 和 undefined 时可使用本法,代码如下:

  1.  var exp = null;  
  2.   
  3. if (!exp)  
  4.   
  5. {  
  6.   
  7.     alert("is null");  
  8.   
  9. }  

如果exp为数字零,也会得到与 null 相同的结果。注意:要同时判断 null、undefined 和数字零时可使用本法,代码如下:

  1.  var exp = null;  
  2.   
  3. if (!exp && exp!=0)  
  4.   
  5. {  
  6.   
  7.     alert("is null");  
  8.   
  9. }   

JavaScript 中没有 isNull 这个函数。

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

注意:exp 为 null 时,typeof 总返回 object。

标签:

给我留言