null :表示無值;
undefined : 表示一個未宣告的變量,
或已聲明但沒有賦值的變量,
或一個不存在的物件屬性。
==運算子將兩者視為相等。如果要區分兩者,請使用===或typeof運算子。
————————————-默默無聞的分割線——————————————–
在JavaScript中,null與undefined一度使人迷惑。下面的分析,有利於你更清晰的認知它(或讓你更迷惑):
- null是關鍵字;undefined是Global物件的一個屬性
- null是物件(空物件, 沒有任何屬性和方法);undefined是undefined類型的值。試試看下面的程式碼:
document.writeln(typeof null); //return object
document.writeln(typeof undefined); //return undefined- 物件模型中,所有的物件都是Object或其子類別的實例,但null物件例外:
document.writeln(null instanceof Object); //return false- null 「等值(==)」於undefined,但不」全等值(===)」於undefined:
document.writeln(null == undefined); //return true
document.writeln(null === undefined); //return false- 運算時null與undefined都可以被型別轉換為false,但不等值為false:
document.writeln(!null, !undefined); //return true,true
document.writeln(null==false); //return false
document.writeln(undefined==false); //return false