JavaScript中Null和Undefined的區別

Null:數組

null是js中的關鍵字,表示空值,null能夠看做是object的一個特殊的值,若是一個object值爲空,表示這個對象不是有效對象。函數

Undefined:對象

undefined不是js中的關鍵字,其是一個全局變量,是Global的一個屬性,如下狀況會返回undefined:blog

1)使用了一個未定義的變量;var i;內存

2)使用了已定義但未聲明的變量;io

3)使用了一個對象屬性,但該屬性不存在或者未賦值;console

4)調用函數時,該提供的參數沒有提供:function

function func(a){
   console.log(a);       
}
func();//undefined

 5)函數沒有返回值時,默認返回undefinedclass

var aa=func();
aa;//undefined

相同點:變量

都是原始類型的值,保存在棧中變量本地

二者的區別:

1.類型不同:

console.log(typeOf undefined);//undefined

console.log(typeOf null);//object

 

2.轉化爲值時不同:undefined爲NaN ,null爲0

console.log(Number(undefined));//NaN
console.log(Number(10+undefined));//NaN

console.log(Number(null));//0
console.log(Number(10+null));//10

 3.undefined===null;//false

    undefined==null;//true

什麼時候使用:

null當使用完一個比較大的對象時,須要對其進行釋放內存時,設置爲null;

var arr=["aa","bb","cc"];
arr=null;//釋放指向數組的引用
相關文章
相關標籤/搜索