JavaScript中Null和undefind區別
阿新 • • 發佈:2017-08-22
cdc 如何 undefine 只有一個 som pre cnblogs 定義 報錯
公眾號原文
Javascript有5種基本類型:Boolean,Number,Null,Undefined,String;和一種復雜類型:Object(對象);
undefined:只有一個值,及特殊的undefined。在使用var聲明變量但未對其初始化時,這個變量的值是undefined,簡言之,undefined就是表示變量申明了但未初始化時的值。
註意:尚未聲明的值直接alert其值會報錯而不是顯示undefined;但是如果一個申明了未賦值的變量與未聲明的變量所顯示的typeof結果是一樣的--->undefined
代碼示例:
<script type="text/javascript"> varstr; alert(typeof str);//undefined alert(typeof message);//undefined </script>
undefined在參與數值運算時一定是NAN,在與字符串拼接相加時則直接顯示undefined;
代碼示例:
<script type="text/javascript"> var b; alert(b+3);//輸出 NAN alert(b+‘3‘);//輸出 undefined3 </script>
null:示準備用來保存對象,還沒有真正保存對象的值。從邏輯角度看,null值表示一個空對象指針。也就是說 null是相對於對象而言的,所以typeof(null) 為object。
null在參與數值計算時其值自動轉換為0,而進行字符串相加拼接時會以字符串“null”的方式顯示
代碼示例:
<script type="text/javascript"> var a=null; alert(null+3+5);//8 alert(null+‘hellow‘);//nullhellow alert(null+3+‘hellow‘);//3hellow alert(null+‘hellow‘+3);//nullhellow3 </script>
聯系:alert(null=undefined);//true ECMAScript認為undefined是由null派生出來的,所以將他們定義為相等。
如何區分?
alert(typeof null == typeof undefined); alert(null === undefined);
JavaScript中Null和undefind區別