在js的日常使用中,经常需要检测数据的类型,现在,就来看一下,js有哪些方法可以检测数据的类型。
typeof
操作符
typeof
操作符返回一个字符串,表示未经计算的操作数的类型。typeof
是js原生提供用来检测类型的API,然而,并没有什么用。
为什么呢?
因为,typeof
不能准确地检测出我们所想要知道的数据的类型。typeof
在大部分情况下都会返回'object'
,如检测array、function、null时。typeof
的唯一作用就是检测变量是否已经被定义。
// 检测变量 xxx 是否被定义
typeof xxx === 'undefined'
// 如果上面判断返回 true,说明变量 xxx 未定义或值为 undefined,这个方法用来避免ReferenceError错误。
复制代码
instanceof
操作符
instanceof
操作符用来检测一个对象的原型链上是否存在某个构造函数的prototype,一般是检测被检测对象的构造函数的prototype。
let obj = new Object()
obj instanceof Objcet // true
let number = new Number(1)
number instanceof Number // true
let arr = []
arr instanceof Array // true
复制代码
instanceof
有一个缺陷:如果数据不是使用构造函数构造出来的,那么结果就会出错。比如:
let str = "asdfghjkl"
str instanceof String // false
复制代码
所以,instanceof
只有在检测自定义的对象时才有用。
实际真正应用的方法
实际开发中,jser使用Object.prototype.toString()
来检测数据类型。Object.prototype.toString()
会返回被调用对象的一个类型字符串,如[object Object]
var class2type = {}
"Boolean Number String Function Array Date RegExp Object Error".split(" ").forEach(function(e,i){
class2type[ "[object " + e + "]" ] = e.toLowerCase()
})
function _typeof(obj){
if ( obj == null ){
return String( obj )
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ Object.prototype.toString.call(obj) ] || "object" :
typeof obj
// 判断 obj 是基本类型还是复杂类型,若是基本类型,直接返回 typeof obj
// 如果 obj 不是基本类型,使用 Object.prototype.toString.call(obj)检测实际类型,若与预定类型匹配,则输出预定类型,否则输出 object
}
复制代码
/**
* getType
* @description 返回给定参数的数据类型
* @param {Any} args 需要做类型检测的参数
* @return {String} args 的数据类型,如 String
*/
function getType(args){
let types = {}
arguments = Array.prototype.slice.call(arguments)
if(arguments.length === 0){
console.log('要查询的参数不存在。')
return
}
let class2type = {}
"Number,String,Boolean,Object,Array,Function,Date,RegExp,Error".split(',').forEach((value,index)=>{
class2type[`[object ${value}]`] = value.toLowerCase()
})
arguments.map((param)=>{
if(param === null){
return types[param] = String(param)
}else if(typeof param === 'object' || typeof param === 'function'){
return types[param] = class2type[Object.prototype.toString.call(param)] || 'object'
}else{
return types[param] = typeof param
}
})
return types
}
// Object.prototype.toString() 会将参数的类型以如 [object Object] 的形式打印出来。
// class2type对象中每一项的属性名都对应一个 toStrign 打印出来的值
// 将 param toString 出来的值与 class2type 进行匹配,就能知晓 param 的类型。
复制代码