JS中檢測數據類型只有四種方式
- 1、typeof 用來檢測數據類型的運算符
[typeof value]
1)返回值:首先是一個字符串,然后包含了我們常用的數據類型,例如:"number"、"string"、"boolean"、"undefined"、"object"、"function" typeof typeof typeof [12] -> "string" 2)typeof null ->"object" 因為null是一個空對象指針 3)typeof不能具體的細分對象、數組、正則等,因為不管檢測哪一個返回的都是"object"
- 2、instanceof / constructor
- 1)instanceof:檢測當前實例是否屬於某一個類,屬於的話返回true,不屬於返回false
var ary=[]; ary instanceof Array ->true ary instanceof RegExp ->false ary instanceof Object ->true 所有的對象都是Object這個基類的一個實例
-
- 2)constructor
ary.constructor===Array ->true 說明ary是Array這個類的一個實例(constructor可以讓用戶自己來修改,所有我們一般不用這個來檢測)
-
- 3)instanceof的局限性:只要在這個實例的原型鏈上的類,用instanceof檢測的時候都為true
在類的繼承中,我們只是單純通過instanceof來檢測數據類型的話是不准確的
[案例]
function Fn() {this.x=100;} Fn.prototype = new Array; var f = new Fn; //f只是繼承了數組中常用的方法,但是不是數組,例如:在梨樹上嫁接蘋果樹,蘋果樹只是繼承使用了梨樹的水分和營養,但是長出來的果實還是蘋果而不是梨 //console.log(f instanceof Fn);//->true //console.log(f instanceof Array);//->true //console.log(f instanceof Object);//->true var oDiv=document.getElementById("div1"); //oDiv->HTMLDivElement->HTMLElement->Element->Node->EventTarget->Object console.log(oDiv instanceof EventTarget);//->true
- 3、toString檢測數據類型(常用而且相對來說精准的檢測方式,上述方式出現的缺陷在這里都彌補了)
- 1)原理:在Object.prototype上有一個toString方法,這個方法執行的時候,會返回方法中this關鍵字對應數據值的數據類型,例如:
//Object.prototype.toString() ->返回的是 Object.prototype 的數據類型 ->"[object Object]" //f.toString() ->返回的是f的數據類型 ->"[object Object]"
-
- 2)這樣的話,我們就可以讓Object.prototype.toString執行,並且通過call/apply來改變里面的this關鍵字,也就是想檢測誰的數據類型,我們就可以讓this變為誰
Object.prototype.toString.call(12) ->檢測12的數據類型 ->"[object Number]" Object.prototype.toString.call("zhufeng") ->"[object String]" Object.prototype.toString.call(null) ->"[object Null]" Object.prototype.toString.call(undefined) ->"[object Undefined]" Object.prototype.toString.call([]) ->"[object Array]" Object.prototype.toString.call(/^$/) ->"[object RegExp]" Object.prototype.toString.call(function(){}) ->"[object Function]"
-
- 3)檢測的返回值 -> "[object 當前數據類型所屬的內置類]"