js-undefinde的一点延伸
前面写过一篇js中变量定义的问题:Js中判断变量存不存在的问题
本文再补充下,变量声明未初始化的情况,代码:
<script> var a; alert(a==undefined)//true </script>
我们看到,声明变量初始化时,默认给了变量一个值,和undefined可以"=="。这个是一种表示"无"的值,还有1个是null。Java中只有null而无undefined.
上面的例子已经知道,变量声明未初始化"=="undefined,那如果是”全等“的情况呢?
<script> var a; alert(a===undefined)//true </script>
运行上面的代码,会弹出true.这里我们知道了未初始化的变量与undefined是“全等“的。这说明, 声明变量初始化时,默认给了变量一个值,就是这个特殊的undefined。
对undefined操作会报错:比如对其用match()方法,报错如下”Uncaught TypeError: Cannot read property 'match' of undefined”。后面的代码将不会执行!
但是,笔者认为,判断一个变量是否为undefined,最好用typeof这个1元运算符。例子如下:
<script> var a; alert(typeof(a)=="undefined");//true </script>
Jquery获取指定元素的属性(attr)时,如果这个元素没有这个属性,会出现什么效果呢?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<li class="perlink">
1111111111111
</li>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(".perlink").click(function(){
alert(typeof($(this).attr("hf"))==="undefined");//true
})
</script>
</body>
</html>
上面代码弹出,是不是跟未声明的变量弹出的很像?事实上,弹出的这个值就是undefined。”全等”运算也是true。那么,就可以这样判断一个页面元素是否用某事属性了,代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<li class="perlink">
1111111111111
</li>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
if(typeof($(".perlink").attr("hf"))!="undefined"){
alert("不空的时候做的事情")
}else{
alert("不做任何事情")
}
</script>
</body>
</html>

浙公网安备 33010602011771号