[JavaScript] JavaScript Number物件的合法型態
有別於一些Strong typing的語言(Java),JavaScript的數值物件(在JS數值型別視為物件)屬於loose typing,這個特性在The Good Parts書中被視為JS的優良部份。number是JavaScript裡唯一的數值型別,合法的數值包含整數、浮點數、指數、特殊值(NaN, Infinity):
整數:
包含正負整數,面試時還被考過16進位(hex)的數值是否合法,答案是可以的
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var num = 1; //positive | |
var num = -1; //negative | |
var num = 0x000f; //hex |
JS的世界1===1.0
指數:
e可以是大寫或小寫
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var expo = 1e2; //100 |
當數字運算無法產生正常結果時,在字串轉數字時最常出現,例:parseInt('google')+12。沒有任何值等於NaN,這表示別用NaN===NaN去檢查運算錯誤,要用isNaN
Infinity:
超過數值可顯示最大值(1.79769313486231570e+308)即會以Infinity表示,不過一般情況下沒有什麼機會超出
上述這些數值只要透過typeof檢查都會回傳number
留言
張貼留言