基本数据类型 string number boolean undefined null
typeof 返回值string number boolean undefined function object
typeof 不能区分object array null,返回值都是object
可以用 obj instanceof Object 返回true则为对象
[1,2] instanceof Array 返回true则为数组
new Date() instanceof Date 返回true则为日期对象
instanceof 判断左边操作数的原型链上是否有右边构造函数的prototype属性*/
也可以用 Object.prototype.toString.apply(x)
var gettype=Object.prototype.toString
gettype.call('aaaa') 输出 [object String]
gettype.call(2222) 输出 [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]
封装为一个函数fun(),可以判断基本数据类型和引用数据类型:
function fun(x){
if(typeof (x)=="object"){
if(Object.prototype.toString.apply(x)==="[object Array]"){
return Array;
}
if(Object.prototype.toString.apply(x)==="[object Date]"){
return Date;
}
if(Object.prototype.toString.apply(x)==="[object Null]"){
return null;
}
if(Object.prototype.toString.apply(x)==="[object Object]"){
return Object;
}
}else{
return typeof(x)
}
}
var a=function(){};
console.log(fun(a));