標籤:lan ber log 數值計算 hello 程式碼範例 類型 nat iad
公眾號原文
Javascript有5種基本類型:Boolean,Number,Null,Undefined,String;和一種複雜類型:Object(對象);
undefined:只有一個值,及特殊的undefined。在使用var聲明變數但未對其初始化時,這個變數的值是undefined,簡言之,undefined就是表示變數申明了但未初始化時的值。
注意:尚未聲明的值直接alert其值會報錯而不是顯示undefined;但是如果一個申明了未賦值的變數與未聲明的變數所顯示的typeof結果是一樣的--->undefined
程式碼範例:
<script type="text/javascript">var str;alert(typeof str);//undefinedalert(typeof message);//undefined</script>
undefined在參與數值運算時一定是NAN,在與字串拼接相加時則直接顯示undefined;
程式碼範例:
<script type="text/javascript">var b;alert(b+3);//輸出 NANalert(b+‘3‘);//輸出 undefined3</script>
null:示準備用來儲存對象,還沒有真正儲存對象的值。從邏輯角度看,null值表示一個Null 物件指標。也就是說 null是相對於對象而言的,所以typeof(null) 為object。
null在參與數值計算時其值自動轉換為0,而進行字串相加拼接時會以字串“null”的方式顯示
程式碼範例:
<script type="text/javascript">var a=null;alert(null+3+5);//8alert(null+‘hellow‘);//nullhellowalert(null+3+‘hellow‘);//3hellowalert(null+‘hellow‘+3);//nullhellow3</script>
聯絡:alert(null=undefined);//true ECMAScript認為undefined是由null派生出來的,所以將他們定義為相等。
如何區分?
alert(typeof null == typeof undefined);alert(null === undefined);
JavaScript中Null和undefind區別