基本數據類型:Undefined、Null、Boolean、Number、String
復雜數據類型 :Object ( Object 類型、Array 類型、Date 類型、RegExp 類型、Function 類型等)
ES6新增數據類型:Symbol
1.typeof? 返回的是一個字符串,表示對象的數據類型,全部以小寫表示
typeof 1 //輸出numbertypeof null //輸出objecttypeof {} //輸出 objecttypeof [] //輸出 objecttypeof (function(){}) //輸出 functiontypeof undefined //輸出 undefined typeof '111' //輸出 string typeof true //輸出 boolean
typeof對于判斷基本的數據類型很有用, 但不能識別null,都把它統一歸為object類型
2. instanceof? 用來判斷 A 是否為 B 的實例,只能用來判斷引用數據類型,?并且大小寫不能錯
var n= [1,2,3];var d = new Date();var f = function(){alert(111);};console.log(n instanceof Array) //trueconsole.log(d instanceof Date) //trueconsole.log(f instanceof Function) //true// console.log(f instanceof function ) //false
3.constructor? 指向對象的構造函數 ——?不推薦使用
var n = [1,2,3];var d = new Date();var f = function(){alert(111);};alert(n.constructor === Array) ----------> truealert(d.constructor === Date) -----------> truealert(f.constructor === Function) -------> true//注意: constructor 在類繼承時會出錯
4.prototype 所有數據類型均可判斷:Object.prototype.toString.call
這是對象的一個原型擴展函數,用來更精確的區分數據類型。
var gettype=Object.prototype.toStringgettype.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節點的判斷,這些東西在我們寫插件的時候都會用到??梢苑庋b的方法如下:
var gettype = Object.prototype.toStringvar 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];??}}