`

判断jquery的null和undefind非空值

阅读更多

 

 

js如何判断变量空值

判断变量是否存在是项目中是经常遇到的问题,list如下:

1,a存在,但a无值
var a;
alert(typeof a === 'undefined');//true 一定要加上(单或双)引号
alert(a == undefined);//true
alert(a === undefined);//true
alert(a == null);//true
alert(a === null);//false 

2,a不存在
alert(typeof a === 'undefined');//true
alert(a == undefined);//error
alert(a === undefined);//error
alert(a == null);//error
alert(a === null);//error

3,a存在,但a是一个占位符null
var a = null;
alert(typeof a === 'undefined');//false
alert(a == undefined);//true
alert(a === undefined);//false
alert(a == null);//true
alert(a === null);//true 

需要根据不同场景选择不同的判断方法,常用的是在函数中,判断实参是否正确的传递进来,通常会用null作为参数的占位符,这里就需要这样判断:
if(typeof a === 'undefined' || a === null )alert('a值出错');

  如果仅想判断非空,可以用 !(xx == undefined) 就行了,若不明白,看下例
        var xx = null;
        var xx2 = undefined;
        if(xx == undefined && xx2 == undefined){
            alert('null == undefined');  // true
        }
体会: 使用的时候如果不能判断 返回的值的类型可以alert(typeof returnValue); 然后就会弹出该值的内容
然后是 比如弹出来的值是 string 那么 你就可以这么判断 if(typeof returnValue == 'string')来确定该值的类型和做判断来写程序

来源:http://blog.sina.com.cn/s/blog_79fded9501016t62.html
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics