写一个getType函数,传入任意变量,获取准确的类型,如number,string,boolean等值类型,和object,array,map,regexp等引用类型。
一般常用的类型判断,我们一般会用这两种来枚举,把尽可能多的类型通过以下2个方法来枚举
- typeof 只能判断值类型
- intanceof 需要两个参数来判断,而不是直接获取类型
但是枚举有很大的可能会遗漏很多类型,因此建议使用Object.prototype.toString.call(x)方法来查询,不能直接调用x.toString()
例如:
const arr = [1,2,3]
arr.toString()
// '1,2,3'
Object.prototype.toString.call(arr)
//'[object Array]'
Object.prototype.toString.call(5)
//'[object Number]'
Object.prototype.toString.call('abc')
//'[object String]'
Object.prototype.toString.call(true)
//'[object Boolean]'
Object.prototype.toString.call({x:100})
// '[object Object]'
Object.prototype.toString.call(() => {})
// '[object Function]'
Object.prototype.toString.call(new Set())
// '[object Set]'
Object.prototype.toString.call(new WeakSet())
// '[object WeakSet]'
Object.prototype.toString.call(new Map())
// '[object Map]'
Object.prototype.toString.call(new WeakMap())
// '[object WeakMap]'
Object.prototype.toString.call(null)
// '[object Null]'
Object.prototype.toString.call(undefined)
// '[object Undefined]'
Object.prototype.toString.call(Symbol())
// '[object Symbol]'
Object.prototype.toString.call(new Date())
// '[object Date]'
Object.prototype.toString.call(new RegExp(''))
// '[object RegExp]' 正则表达式
Object.prototype.toString.call(new Error())
// '[object Error]'
Object.prototype.toString.call(Promise.resolve())
// '[object Promise]' 不能直接call(Prpmise)
Object.prototype.toString.call(NaN)
//'[object Number]' NaN属于Number类型
Object.prototype.toString.call(Infinity)
//'[object Number]' Infinity属于Number类型
Object.prototype.toString.call(-Infinity)
//'[object Number]' -Infinity属于Number类型
Object.prototype.toString.call(BigInt(10000))
//'[object BigInt]'
其他的就暂不列举了
function getType(x: any): string {
const originType = Object.prototype.toString.call(x)
// '[object Array]'
// 先获取类型,后面就是字符串转换
const index = originType.indexOf(' ')
const type = originType.slice(index + 1, -1)
// 'Array'
return type.toLowerCase()
// 'array'
}