null和undefined的概述

一,null

null是JavaScript語言的關鍵字,它表示一個特殊值,經常使用來描述「空值」,對null執行typeof預算,結果返回字符串"object";值null 是一個字面量,它不像undefined 是全局對象的一個屬性!函數

typeof null        // "object" 
var a = null;
typeof(a);        // "object" 
複製代碼

出現null的狀況:

  • 手動設置變量的值或者對象某一個屬性值爲null時。
var obj = {
    name: null,
    age: 18
};
console.log(obj.name);
複製代碼
  • 在JS的DOM元素獲取中,若是沒有獲取到指定的元素對象,結果通常是null。
<body>
    <button id="btn">我是一個按鈕</button>
    <script>
        var btn = document.getElementById('abc');   
        console.log(btn);       //  null
    </script>
</body>
複製代碼
  • 在正則捕獲的時候,若是沒有捕獲到結果,默認也是null。

二,undefined

undefined是全局對象的一個屬性。也就是說,它是全局做用域的一個變量。undefined的最初值就是原始數據類型undefined。ui

出現undefined的狀況

  • 變量聲明沒有賦值返回undefined
var a;
console.log(a);     // undefined
複製代碼
  • 函數沒有返回值時,默認返回undefined
function fun(x) {

}
fun(1);           // undefined
複製代碼
  • 調用函數時,應該提供的參數沒有提供,返回undefined
function fun(a){
    return a;
}
fun();           // undefined
複製代碼
  • 對象沒有賦值的屬性,該屬性的值爲undefined
var obj = {
    name: 'Andy'
}
obj.age;        // undefined
複製代碼
相關文章
相關標籤/搜索