使用Object.prototype上的原生toString()方法判断数据类型,使用方法如下:
Object.prototype.toString.call(value)
1.判断基本类型:
1 | Object.prototype.toString.call(null);//”[object Null]” |
2.判断原生引用类型:
函数类型
1 | Function fn(){console.log(“test”);} |
日期类型
1 | var date = new Date(); |
数组类型
1 | var arr = [1,2,3]; |
正则表达式
1 | var reg = /[hbc]at/gi; |
自定义类型
1 | function Person(name, age) { |
很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断,如下所示:
1 | console.log(person instanceof Person);//输出结果为true |
3.判断原生JSON对象:
1 | var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON); |
注意:Object.prototype.toString()本身是允许被修改的,而我们目前所讨论的关于Object.prototype.toString()这个方法的应用都是假设toString()方法未被修改为前提的。
1 | console.log(Object.prototype.toString.call("jerry"));//[object String] |
(无法区分自定义对象类型,自定义类型可以采用instanceof区分)
JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。
对于数组、函数、对象来说,其关系复杂,若使用 typeof 都会统一返回 为object,这样为后续处理带来不便。
关键函数方法
js原生方法Object.prototype.toString.call();它可以给出数据的确切类型,相比typeof要精确。
1 | function getDataType(data){ |