JS 判断变量是否为空

来源:互联网 发布:软件开发可行性分析 编辑:程序博客网 时间:2024/04/29 01:18

下面是js中的"!"对null(Object),""(String),0(number),undefined四种类型进行是否为空的判断。

这四种类型的变量,都能通过!判断出空来。

下面的代码直接粘贴到记事本中,保存成后缀为.html(例如:a.html)的文件就可以运行。


<script type="text/javascript">



var a=null;
var b="";
var c=0;
var d=" ";
var e;
alert(typeof a);
alert(typeof b);
alert(typeof c);
alert(typeof d);
alert(typeof e);


if(!a){
alert("a is null");
}else{
alert("a is not null");
}
if(!b){
alert("b is null");
}
if(!c){
alert("c is null");
}
if(!d){
alert("d1 is null");
}else{
d = d.replace(/(^\s*)|(\s*$)/g, "");
if(!d){
alert("d2 is null");
}else{
alert("d2 is not null");
}
}
if(!e){
alert("e is null");
}


</script>
0 0
原创粉丝点击