JS數據類型檢驗

咱們知道判斷數據類型能夠用typeof函數

定義一些數據ui

let num=1,str='str',bool=true,obj={},arr=[],sy=Symbol('s'),g,reg=/test/,date=new Date()

typeof運算符this

typeof num //"number"
typeof str //"string"
typeof bool //"boolean"
typeof g //"undefined"
typeof obj //"object"
typeof arr //"object"
typeof reg//"object"
typeof date //"object"
typeof null //"object"

能夠看出來typeof 對基本類型(除了null)能夠判斷出類型,可是對應對象,沒有辦法知道具體的類型prototype

instanceof 判斷是否爲每一個類型的實例,經過這個方法能夠判斷出類型,咱們對上述數據進行判斷code

function Person(){}
let p=new Person()
function Foo(){}
let f=new Foo()
num instanceof Number //false 
str instanceof String //false
arr instanceof Object //true
arr instanceof Array //true 
obj instanceof Object //true 
obj instanceof Array //false 
reg instanceof RegExp //true
date instanceof Date //true

constructor對象

arr.constructor ===Array //true 
obj.constructor ===Object //true 
str.constructor === String  //true

從輸出的結果咱們能夠看出,除了undefined和null,其餘類型的變量均能使用constructor判斷出類型。
不過使用constructor也不是保險的,由於constructor屬性是能夠被修改的,會致使檢測出的結果不正確繼承

Object.prototype.toString.call原型鏈

Object.prototype.toString.call(str) //"[object String]"

Object.prototype.toString.call(obj) //"[object Object]"

Object.prototype.toString.call(null) //"[object Null]"

Object.prototype.toString.call(num) ///"[object Number]"

...

每一個對象都有一個toString()方法,當該對象被表示爲一個文本值時,或者一個對象以預期的字符串方式引用時自動調用。默認狀況下,toString()方法被每一個Object對象繼承。若是此方法在自定義對象中未被覆蓋,toString() 返回 "[object type]",其中type是對象的類型字符串

那爲何Object.toString.call(params) 會報錯呢?原型

Object.toString.call(num)

Uncaught TypeError: Function.prototype.toString requires that 'this' be a Function at Number.toString (<anonymous>) at <anonymous>:1:17

這是爲何呢,由於Object爲構造函數,Object構造函數自己沒有toString方法。依照原型鏈關係,Object構造函數的上游原型鏈是Function.prototype。因此,你調用Object.toString.call(param)本質上是調用Function.prototype.toString.call(param),這裏須要的參數類型是函數,因此會報錯。

相關文章
相關標籤/搜索