** js基本數據類型有哪些?**
5種簡單數據類型:Null、Boolean、String、Number、Undefined
1種復雜數據類型:Object
-
undefined
- 是var聲明的變量,但未進行初始化的默認值
var message;
alert(message); //"undefined"
alert(age); //尚未定義的變量,會報錯,需要用typeof操作符進行判斷
- 未聲明的變量typeof操作符返回的值
alert(age); //產生錯誤
alert(typeof age); // "undefined"
-
null
- 邏輯上來看,null值表示空對象指針,而這也正是typeof操作符檢測返回“object”的原因。
var car =null;
alert(typeof car); //"object"
定義的變量,將來為了保存對象(即復雜的數據類型object),則初始化為null
-
區別
實際上,undefined是null的派生,ECMA-262規定它們的相等性測試返回true
alert(undefined==null);//true
雖然有這樣的關系,但是用途卻不一樣。
undefined是變量未初始化或未定義的默認值,typeof操作符檢測也為"undefined";
但是,null表示變量被定義為“空值”,其typeof操作符檢測為"object"-
典型用法
- null
- 作為函數的參數,表示該函數的參數不是對象。
- 作為對象原型鏈的終點。
- undefined
- 聲明的變量,未初始化,變量的值為undefined
- 調用函數時,應該提供的參數沒有提供,該參數等于undefined。
- 對象的屬性沒有賦值,屬性的值為undefined
- 函數沒有返回值時,默認返回undefined
參考文章:undefined與null的區別