undefined、null应用场合

在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'来进行判断,可准确地判空,且不会抛出异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值