加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

js如何判断变量空值

(2012-08-09 11:20:43)
标签:

js

判断为空

it

分类: jquery那些事

js如何判断变量空值

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

1,a存在,但a无值
var a;
alert(typeof === 'undefined');//true
alert(a == undefined);//true
alert(a === undefined);//true
alert(a == null);//true
alert(a === null);//false

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

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

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

yui也提供了这两种方法
Y.Lang.isUndefined(a);


Y.Lang.isNull(a);

但是Y.Lang.isUndefined(a);会有问题,如果a真的不存在会报错
体会: 使用的时候如果不能判断 返回的值的类型可以alert(typeof returnValue); 然后就会弹出该值的内容
然后是 比如弹出来的值是 string 那么 你就可以这么判断 if(typeof returnValue == 'string')来确定该值的类型和做判断来写程序

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有