在JavaScript 中,经常会用到undefined和null,这里面还有些小的诀窍。undefined顾名思义就是未定义,也就是程序中没有声明过;null则是虽然声明了,但没有赋值。
1、场景1
对于没有声明或定义的变量a,适合的空判断方法是typeof(a) ==‘undefined’方式,而不适合用a==undefined或a==null判断。
if(typeof a == 'undefined'){
alert('a is not defined.');
}
try{
if(a == undefined){
alert('2a is not defined.');
}
if(a == null){
alert('a is null.');
}
}catch(e){
}
2、场景2
对于已经声明的变量a,使用typeof(a) ==‘undefined’方式,a==undefined或a==null判断均可以得出正确结果。
var b;
if(b == undefined){
alert('b is not defined. ')
}
if(b==null){
alert('b is null.');
}
if(typeof b == 'undefined'){
alert('b undefined. ')
}
3、场景3
对于函数参数的空判断,使用typeof(a) ==‘undefined’方式,a==undefined或a==null三种方式均可。
function fun(p1,p2,p3){
if(p3 == undefined){
alert('p3 not defined.');
}
if(typeof p3 == 'undefined'){
alert('p3 NOT defined.');
}
if(p3 == null){
alert('p3 is null.');
}
alert(p1 +',' + p2 + "," + p3);
}
fun(1,null);
可以看到,p3参数未输入,但可以使用p3==undefined和p3==null来判断空,这是以因为参数中已声明p3参数。
p2传入了null值,其值不再是undefined,而修改为null。
4、总结
综上所述,对于函数的参数,可以用a==null做空判断比较合适,不论传入的是否是null值、undefined值,还是未传入值,都可以用null进行判断。
对于函数外的参数,若不确定已定义,则应用 typeof(a) ==''undefined'来进行判断,可准确地判空,且不会抛出异常。