js檢測資料型別的四種方式

2022-07-15 10:03:15 字數 1145 閱讀 7646

js常見的資料型別分為兩種,第一種是基本資料型別(string、number、null、undefined、boolean、symbol、bigint),第二種是引用資料型別(object、array、regexp...)

常見的檢測資料型別方式:

1)typeof

2) instanceof

3) constructor

4) object.prototype.tostring.call()

typeof

1) 定義:能夠檢測基本型別的符號

2)語法:typeof[value]

3) 返回值:[string、number、undefined、function、object]

4) 缺點:1)不能夠檢測物件屬於哪一種資料型別,例如陣列物件、regexp物件統一返回object

2)typeof null返回的是物件(object)

3)nan/infinity返回的是number

instanceof

1)  定義:用於檢測建構函式的 prototype 屬性是否出現在某個例項物件的原型鏈上。

2)語法:object instanceof value

3) 返回值:boolean

4) 缺點:

1 ) 無法檢測基本型別,返回的都是false ,只能檢測複雜資料型別

2)由於instanceof是根據原型來檢測型別的,返回值也是布林型別,因此無法直觀的看出資料型別

3) 因為原型可以更改,有時候利用instanceof來判斷不一定十分準確

constructor

1)定義 : 通過構造器來判斷型別。

2)語法 : target.constructor == "型別名字"

3)返回值:boolean

4)缺點:原理基本和instanceof一樣,都是根據原型判斷

object.prototype.tostring.call()

1) 定義 : 返回乙個表示該物件的字串。

2) 語法 : object.prototype.tostring.call(params)

3) 返回值 : "[object 型別]"

資料型別檢測的四種方式

typeof 檢測資料型別的運算子 返回的都是乙個字串 型別 number string boolean undefined function object console.log typeof 12 console.log typeof 14 console.log typeof undefine...

js學習總結 資料型別檢測的四種方式

1 typeof 用來檢測資料型別的運算子 console.log typeof 12 number 使用typeof檢測資料型別,首先返回的都是字串 其次字串中包含了對應的資料型別 例如 number string boolean undefined function object console...

js檢測資料型別四種辦法

1.typeof console.log typeof string console.log typeof 1 number console.log typeof true boolean console.log typeof null object console.log typeof undef...