JavaScript 中的undefined and null 學習

JavaScript 中的undefined and null learn record from the definitive guide to html5

JavaScript 中有兩個特殊值:undefined and null,javascript

在讀取未賦值的變量或試圖讀取對象沒有的屬性時獲得的就是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>

輸出:html

prop: undefined

null 表示已經賦值給了一個值,可是該值不是一個有效的object,string,number,boolean 值(也就是說所定義的是一個無值[no value]).

例子:html5

<!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>

輸出:java

var:undefined prop:false 
var:sunny prop:true 
var:null prop:true

undefined and null的相等和等同比較

例子:ide

<!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>

輸出:ui

equality:true 
identity:false
相關文章
相關標籤/搜索