ECMAScript有5種基礎資料型別 (Elementary Data Type)Undefined ,Null ,Boolean ,Number ,String 和一種複雜類型 Object
1. Undefined
Undefined類型只有一個值,即特殊的undefined
2. Null
Null類型只有一個值,即特殊的null
如果定義的變數準備用於儲存對象,那麼最好將該變數初始化為null,這樣就知道該變數儲存了一個對象的引用。
注意:null 和 undefined 之間的相等操作符(==)總是返回true
3.Boolean
Boolean類型只有兩個值:true 和 false
要將其他類型轉換為Boolean,要調用轉型函數Boolean(),任何非零數,任何除null以外的對象轉為true,0和NaN,null,undefined轉換為false
View Code
var m = "hello";var mAsBoolean = Boolean(m);var m1 = 2000;var m1AsBoolean = Boolean(m1);var m2 = new Object();var m2AsBoolean = Boolean(m2);var m3AsBoolean = Boolean(null);var m4AsBoolean = Boolean(0);var m5AsBoolean = Boolean(NaN);var m6AsBoolean = Boolean(undefined);alert("mAsBoolean = Boolean(m):" + mAsBoolean + "\n\r" + "m1AsBoolean= Boolean(m1) :" + m1AsBoolean + "\n\r" + "m2AsBoolean= Boolean(m2):" + m2AsBoolean + "\n\r" + "m3AsBoolean= Boolean(null):" + m3AsBoolean + "\n\r" + "m4AsBoolean= Boolean(0):" + m4AsBoolean + "\n\r" + "m5AsBoolean= Boolean(NaN) :" + m5AsBoolean + "\n\r" + "m6AsBoolean= Boolean(undefined):" + m6AsBoolean);
查看結果
4.Number
ECMAScript中,用IEEE754格式來表示整數和浮點數,因為Number()函數在轉換字串時比較複雜,而且不夠合理,所以一般用parseInt(),parseFloat()
View Code
var octnum = "070"; var hexnum = "0xa"; var intnum = 56; var floatNum = 1.389; var str = "hello"; var str1 = "123hi"; var str2 = "hello456"; var str3 = "test789hi"; alert("Number(octnum):" + Number(octnum) + "," + 'parseInt(octnum,8):' + parseInt(octnum, 8) + "," + 'parseInt(octnum)' +parseInt(octnum)+"\n\r" + "Number(hexnum):" + Number(hexnum) + "," + 'parseInt(hexnum,16):' + parseInt(hexnum, 16) + "," + 'parseInt(hexnum)' +parseInt(hexnum)+"\n\r" + "Number(intnum):" + Number(intnum) + "," + 'parseInt(intnum,10):' + parseInt(intnum, 10) + "," + 'parseInt(intnum)' +parseInt(intnum) +"\n\r" + "Number(floatNum):" + Number(floatNum) + "," + 'parseFloat(floatNum):' + parseFloat(floatNum) + "\n\r" + "Number(str):" + Number(str) + "," + 'parseInt(str):' + parseInt(str) + "," + 'parseFloat(str)' + parseFloat(str) + "\n\r" + "Number(str1):" + Number(str1) + "," + 'parseInt(str1):' + parseInt(str1) + "," + 'parseFloat(str1)' +parseFloat(str1)+ "\n\r" + "Number(str2):" + Number(str2) + "," + 'parseInt(str2):' + parseInt(str2) + "," + 'parseFloat(str2)' + parseFloat(str2)+"\n\r" + "Number(str3):" + Number(str3) + "," + 'parseInt(str3):' + parseInt(str3) + "," + 'parseFloat(str3)' + parseFloat(str3));
查看結果
5. String
String 類型用於表示由零或多個16位的Unicode字元組成的字元序列,,字串可以由雙引號或單引號表示。
要把一個值轉換為字串,有兩種方法:
1是每個值都有一個toString()方法,預設情況下toString()方法以10進位格式返回數值字串,也可以傳遞基數。
例如: var num=100;num.toString(16);
2在不知道要轉換的類型是不是null或undefined的情況下,可以用String()。
String()遵循的轉換規則為:如果此值有toString()方法,就調用toString(),如何值為null,則返回“null”;如果值為undefined,則返回undefined
6 Object比較複雜,到時候單獨拿出來總結