JavaScript 中的undefined and null learn record from the definitive guide to html5
JavaScript 中有两个特殊值:undefined and null,
在读取未赋值的变量或试图读取对象没有的属性时得到的就是undefined值。
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
var myData = {
name: "admin",
weather: "sunny"
};
document.writeln("prop:" + myData.doesntexist);
</script>
</body>
</html>
输出:
prop: undefined
null 表示已经赋值给了一个值,但是该值不是一个有效的object,string,number,boolean 值(也就是说所定义的是一个无值[no value]).
例子:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
var myData = {
name: "admin"
};
document.writeln("var:" + myData.weather);
document.writeln("prop:" + ("weather" in myData));
document.writeln("</br>");
myData.weather = "sunny";
document.writeln("var:" + myData.weather);
document.writeln("prop:" + ("weather" in myData));
document.writeln("</br>");
myData.weather = null;
document.writeln("var:" + myData.weather);
document.writeln("prop:" + ("weather" in myData));
</script>
</body>
</html>
输出:
var:undefined prop:false
var:sunny prop:true
var:null prop:true
undefined and null的相等和等同比较
例子:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
var firstVal = null;
var secondVal ;
var equality = firstVal == secondVal;
var identity = firstVal === secondVal;
document.writeln("equality:" + equality);
document.writeln("</br>");
document.writeln("identity:" + identity);
</script>
</body>
</html>
输出:
equality:true
identity:false