一般在js判断数据类型时,主要有以下几种方法:typeof、instanceof、constructor、prototype、$.type/jQuery.type
接下来我们来比较下各种方法的异同
var a = 'string'
typeof(a) =====>string
a.constructor == String =====>true
Object.prototype.toString.call(a) =====>"[object String]"
$.type(a) =====>string
var b = 420
typeof(b) =====>number
b.constructor == Number =====>true
Object.prototype.toString.call(b) =====>"[object Number]"
$.type(b) =====>number
var c = [1990, 4, 20]
typeof(c) =====>object
c instanceof Object =====>true
c.constructor == Array =====>true
Object.prototype.toString.call(c) =====>"[object Array]"
$.type(c) =====>array
var d = undefined
typeof(d) =====>undefined
Object.prototype.toString.call(d) ======>"[object Undefined]"
$.type(d) =====>undefined
var e = null
typeof(e) =====>object
e instanceof Object =====>false
Object.prototype.toString.call(e) =====>"[object Null]"
$.type(e) =====>null
var f = {a:'b'}
typeof(f) =====>object
f instanceof Object =====>true
f.constructor == Object =====>true
Object.prototype.toString.call(f) =====>"[object Object]"
$.type(f) =====>object
var g = new Date()
typeof(g) =====>object
g instanceof Object =====>true
g.constructor == Date =====>true
Object.prototype.toString.call(g) =====>"[object Date]"
$.type(g) =====>date
var h = function(){}
typeof(h) =====>function
h instanceof Function =====>true
h.constructor == Function =====>true
Object.prototype.toString.call(h) =====>"[object Function]"
$.type(h) =====>function
对于instanceof,一般是在我们已知数据类型时进行判断,但一定要注意类型名的大小写。对于constructor,我们一般要注意类继承的问题:
function a () {}
function b () {}
a.prototype = new b() //a继承b
var obj = new a()
obj.constructor == a =====>false
obj.constructor == b =====>true
使用instanceof 不会出现该类问题:
obj instanceof a =====>true
obj instanceof b =====>true
使用prototype时同样要注意大小写的问题。
而$.type则是比较万能的方法了,可以判断布尔、error、正则等等
$.type(false) =====>boolean
$.type(new Error()) =====>error
$.type(/\d/) =====>regexp