typeof a
-
可以判别标准类型,除了null之外
typeof 1
返回结果:"number"typeof {}
返回结果:"object" -
不能判别具体的对象类型,除了function之外
typeof [1]
返回结果:"object"typeof function(){}
返回结果:"function"
a instanceof b
-
可以判别内置对象类型
[] instanceof Array
返回结果:truenew String() instanceof String
返回结果:true -
不能判别原始类型值
'a' instanceof String
返回结果:false -
可以判别自定义对象类型
function Point(x,y){ this.x = x; this.y = y } var c = new Point(1,2) c instanceof Point
返回结果:true
a.constructor
-
可以判别标准数据类型(undefined和null除外)
'123'.constructor == String
返回结果:true -
可以判别具体的内置对象类型
[1,2].constructor == Array
返回结果:true -
可以判别自定义对象类型
function Point(x,y){ this.x = x; this.y = y } var c = new Point(1,2) c.constructor == Point
返回结果:true
Object.prototype.toString.call(a)
-
可以判别标准数据类型
Object.prototype.toString.call(1)
返回结果:"[object Number]"Object.prototype.toString.call(undefined)
返回结果:"[object Undefined]" -
可以判别内置对象类型
Object.prototype.toString.call([a])
返回结果:"[object Array]" -
不能判别自定义对象类型
function Point(x,y){
this.x = x;
this.y = y
}
var c = new Point(1,2)
Object.prototype.toString.call(c)
返回结果:"[object Object]"
工作中可以写一个函数方便判定
function type(obj){
return Object.prototype.toString.call(obj).slice(8,-1)
}
type('a')
返回结果: "String" type([a])
返回结果: "Array"