判斷資料型別的幾種方法

2021-09-28 10:34:10 字數 1688 閱讀 7637

let arr =

['name'

,'age'

]arr.

tostring()

;// "name,age"

object.prototype.tostring.

call

(arr)

// "[object array]"

該方法對於所有基本的資料型別都能進行判斷,null和undefined也行

object.prototype.tostring.

call

('jackson'

)// "[object string]"

object.prototype.tostring.

call

(852

)// "[object number]"

object prototype.tostring.

call

(symbol

(852))

// "[object symbol]"

object.prototype.tostring.

call

(null

)// "[object null]"

object.prototype.tostring.

call

(undefined)

// "[object undefined]"

object.prototype.tostring.

call

(function()

)// "[object function]"

object.prototype.tostring.

call()

// "[object object]"

object.prototype.tostring.call()常用於判斷瀏覽器內建物件,但是object.prototype.tostring.call()不能校驗自定義型別

function

jacky()

let a =

newjacky()

object.prototype.tostring.

call

(a)// "[object object]"

instanceof的內部機制是通過判斷物件的原型鏈中是不是能找到型別的prototype

使用instanceof判斷乙個物件是否為陣列,instanceof會判斷這個物件的原型鏈上是否會找到對應的array原型,找到返回true,否則返回false

[

]instanceof

array

// true

但instanceof只能用來判斷物件型別,原始型別不可以。並且所有物件型別instanceof object 都是true

[

]instanceof

object

// true

'a'instanceof

string

// false

typeof只能檢測基本資料型別,包括boolean、undefined、string、undefined、function、symbol,而null、array、object,使用typeof出來都是object。無法檢測具體是那種引用型別。

判斷資料型別幾種方法

常用的判斷資料型別的方法主要有 typeof,instanceof,constructor,object.prototype.tostring 下面來分別介紹 1 typeof 返回乙個字串,表示未經計算的運算元的型別。console.log typeof 42 number 缺點 對於陣列和物件或...

js判斷資料型別幾種方法

js資料型別的判斷主要有四種方法 typeof instanceof constructor object.prototype.tostring.call 資料型別的包括 number boolean string symbol object array undefined null functio...

Flex判斷資料型別的幾種方法

判斷資料型別,主要有一下幾種as instanceof,is,typeof。1 as 計算第乙個運算元指定的表示式是否是第二個運算元指定的資料型別的成員。如果第乙個運算元是該資料型別的成員,則結果是第乙個運算元。否則,結果是null 值。舉例 public var myarray array one...