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

typeof 1 //輸出number
typeof null //輸出object
typeof {} //輸出 object
typeof [] //輸出 object
typeof (function(){}) //輸出 function
typeof undefined //輸出 undefined
typeof '111' //輸出 string
typeof true //輸出 boolean
typeof對于判斷基本的數(shù)據(jù)類型很有用, 但不能識別null,都把它統(tǒng)一歸為object類型
2. instanceof? 用來判斷 A 是否為 B 的實例,只能用來判斷引用數(shù)據(jù)類型,?并且大小寫不能錯
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 在類繼承時會出錯
4.prototype 所有數(shù)據(jù)類型均可判斷:Object.prototype.toString.call 這是對象的一個原型擴展函數(shù),用來更精確的區(qū)分?jǐn)?shù)據(jù)類型。
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 中還有很多類型可以判斷,如 [object HTMLDivElement] div 對象 [object HTMLBodyElement] body 對象 [object Document](IE) [object HTMLDocument](firefox,google) 等各種dom節(jié)點的判斷,這些東西在我們寫插件的時候都會用到??梢苑庋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];
??}
}
|