基本數(shù)據(jù)類(lèi)型:Undefined、Null、Boolean、Number、String 復(fù)雜數(shù)據(jù)類(lèi)型 :Object ( Object 類(lèi)型、Array 類(lèi)型、Date 類(lèi)型、RegExp 類(lèi)型、Function 類(lèi)型等) ES6新增數(shù)據(jù)類(lèi)型:Symbol
1.typeof? 返回的是一個(gè)字符串,表示對(duì)象的數(shù)據(jù)類(lèi)型,全部以小寫(xiě)表示

typeof 1 //輸出number
typeof null //輸出object
typeof {} //輸出 object
typeof [] //輸出 object
typeof (function(){}) //輸出 function
typeof undefined //輸出 undefined
typeof '111' //輸出 string
typeof true //輸出 boolean
typeof對(duì)于判斷基本的數(shù)據(jù)類(lèi)型很有用, 但不能識(shí)別null,都把它統(tǒng)一歸為object類(lèi)型
2. instanceof? 用來(lái)判斷 A 是否為 B 的實(shí)例,只能用來(lái)判斷引用數(shù)據(jù)類(lèi)型,?并且大小寫(xiě)不能錯(cuò)
var n= [1,2,3];
var d = new Date();
var f = function(){alert(111);};
console.log(n instanceof Array) //true
console.log(d instanceof Date) //true
console.log(f instanceof Function) //true
// console.log(f instanceof function ) //false
3.constructor? 指向?qū)ο蟮臉?gòu)造函數(shù) ——?不推薦使用
var n = [1,2,3];
var d = new Date();
var f = function(){alert(111);};
alert(n.constructor === Array) ----------> true
alert(d.constructor === Date) -----------> true
alert(f.constructor === Function) -------> true
//注意: constructor 在類(lèi)繼承時(shí)會(huì)出錯(cuò)
4.prototype 所有數(shù)據(jù)類(lèi)型均可判斷:Object.prototype.toString.call 這是對(duì)象的一個(gè)原型擴(kuò)展函數(shù),用來(lái)更精確的區(qū)分?jǐn)?shù)據(jù)類(lèi)型。
var gettype=Object.prototype.toString
gettype.call('a') \\ 輸出 [object String]
gettype.call(1) \\ 輸出 [object Number]
gettype.call(true) \\ 輸出 [object Boolean]
gettype.call(undefined) \\ 輸出 [object Undefined]
gettype.call(null) \\ 輸出 [object Null]
gettype.call({}) \\ 輸出 [object Object]
gettype.call([]) \\ 輸出 [object Array]
gettype.call(function(){}) \\ 輸出 [object Function]
js 中還有很多類(lèi)型可以判斷,如 [object HTMLDivElement] div 對(duì)象 [object HTMLBodyElement] body 對(duì)象 [object Document](IE) [object HTMLDocument](firefox,google) 等各種dom節(jié)點(diǎn)的判斷,這些東西在我們寫(xiě)插件的時(shí)候都會(huì)用到??梢苑庋b的方法如下:
var gettype = Object.prototype.toString
var utility = {
??isObj:function(o){
????return gettype.call(o)=="[object Object]";
??},
??isArray:function(o){
????return gettype.call(o)=="[object Array]";
??},
??isNULL:function(o){
????return gettype.call(o)=="[object Null]";
??},
??isDocument:function(){
????return gettype.call(o)=="[object Document]"|| [object HTMLDocument];
??}
}
|