typeof 1 // "number" typeof "a" // "string" typeof true // "boolean" typeof {} // "object" typeof [] // "object" typeof function(){} // "function"
使用时的一个问题是,在判断数组和对象存储值时,都返回”object”。
Object.prototype上的原生toString()方法判断数据类型Object.prototype.toString.call(2);//"[object Number]" Object.prototype.toString.call("s");//"[object String]" Object.prototype.toString.call(true);//"[object Boolean]"判断空类型
Object.prototype.toString.call(null);//"[object Null]" Object.prototype.toString.call(undefined);//"[object Undefined]"
// 堆代码 duidaima.com Object.prototype.toString.call({});//"[object Object]" Object.prototype.toString.call([]);//"[object Array]" Object.prototype.toString.call(function(){});//"[object Function]" Object.prototype.toString.call(String);//"[object Function]" var t = new Date(); Object.prototype.toString.call(t);//"[object Date]" var bb = new Boolean(); Object.prototype.toString.call(bb);//"[object Boolean]" var bb = new Number(); Object.prototype.toString.call(bb);//"[object Number]" var str = new String(); Object.prototype.toString.call(str);//"[object String]" var reg = new RegExp("^1[34578][0-9]{9}$","g"); Object.prototype.toString.call(reg);//"[object RegExp]" var reg = Math.valueOf(); Object.prototype.toString.call(reg);//"[object Math]"判断原生JSON对象
var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON); console.log(isNativeJSON);//[object JSON]判断自定义类型
function Foo(name,age) { this.name = name; this.age = age; } var foo =new Foo("harry",20); Object.prototype.toString.call(foo);//"[object Object]"
遇到的一个问题是,使用Object.prototype.toString.call()方法不能判断foo是Foo类的实例。只能用instanceof来判断。
console.log(foo instanceof Foo);//true