js中的基本型別有:數字(number(nan,infinity)),字串(string),undefined,null,boolean
引用型別有:陣列(array),物件(object),函式(function),日期(data),正則(regexp)
鑑別型別一般使用typeof關鍵字,但是typeof運算子有很多坑:
1:對null返回的是object,但是不能將屬性和方法加在null身上。
2:對nan和infinity返回的是number,但是這兩個量是不可以用來做數值計算的。
3:不能區分物件,陣列,data,正則及null,都返回的是object。
最完整的方法是使用object.prototype.tostring方法(前提是此方法沒有被重寫的情況下)來鑑別各種型別。
typeof
object.prototype.tostring.call(xx)
number
number
[object number]
nannumber
[object number]
infinity
number
[object number]
string
string
[object string]
undefined
undefined
[object undefined]
null
object
[object null]
bool
boolean
[object boolean]
array
object
[object array]
objobject
[object object]
funfunction
[object function]
data
object
[object data]
regexp
object
[object regexp]
此方法唯一的缺點就是沒辦法區分nan,infinity和number,其實從本質上說nan和infinity是number的兩個特例,所以按照number來標識也不錯,只是以後遇見需要判斷裡的時候要先排除這兩個特例再輔之object.prototype.tostring.call()就能完善的區分各種型別了.
js中型別判斷
剛接觸js的時候,用typeof 來判斷,可是發現用來判斷一些簡單型別還可以,但是物件就無法判斷的,都是返回object 後來發現可以用object.prototype.tostring.call o 來判斷o的型別,返回 object array object date object undefi...
JS中型別的檢測
在js開發中,經常需要檢測乙個變數的型別。現在就總結一下常見的檢測變數型別的方法,以及它們的適用場景。一 typeof 要檢測乙個變數是不是基本資料型別,typeof是最佳的工具。也就是說,typeof是確定乙個變數是字串 數值 布林值還是undefined的最佳工具。但如果變數是乙個物件或者nul...
js中 基本包裝型別
為了便於操作基本型別,ecmascript還提供了3個特殊的引用型別boolean number string。這些型別與其他引用型別形似,但同時也具有各自的基本型別相應的特殊行為。實際上,每當讀取乙個基本型別值時後台就會建立乙個相應的基本包裝型別的物件,從而讓我們能夠呼叫一些方法來操作這些資料。e...