undefined null测试

本文通过测试示例展示了在Chrome浏览器环境下,JavaScript中undefined与null的比较及类型判断的差异。并通过具体代码演示了如何避免因变量未定义而引发的错误。
测试浏览器:chrome
当有父元素的子元素未定义时undefined和null均为true,类型为undefined
当元素赋给null后undefined和null均为true,类型为object,因此建议设置为null
当直接用未定义顶级元素x时,无论是x==undefined或if(x)都会报错
function log(o){
    console.log(o);
}
function lognull(o){
    log(o==undefined)
    log(o==null)
    log(typeof o)
}  
var a={aa:'bb'}
var c=null;
lognull(a.ff)//未定义子元素不会报错
lognull(c)
//以下,未定义顶级元素会报错
lognull(d)
if(dd){ //Uncaught ReferenceError: dd is not defined
}
 
 
 
测试结果
true
true
undefined
true
true
object
 Uncaught ReferenceError: d is not defined
-------------------------
 全部代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>


<script type="text/javascript">
function log(o){
    console.log(o);
}
function lognull(o){
    log(o==undefined)
    log(o==null)
    log(typeof o)
}
function notHave(o){
    if(o==undefined){return true;}
    if(o==null){return true;}
//    if((typeof o)==undefined){return true;}
    return false;
}

var a={aa:'bb'}
var c=null;
lognull(a.ff)//未定义子元素不会报错
lognull(c)
//以下,未定义顶级元素会报错
lognull(d)
if(dd){ //Uncaught ReferenceError: dd is not defined

}
</script>
</head>

<body>
</body>
</html>
View Code

 



 

转载于:https://www.cnblogs.com/stit/p/6367785.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值