写一个getType方法,获取所有的javascript数据类型

写一个getType函数,传入任意变量,获取准确的类型,如number,string,boolean等值类型,和object,array,map,regexp等引用类型。

一般常用的类型判断,我们一般会用这两种来枚举,把尽可能多的类型通过以下2个方法来枚举

  1. typeof 只能判断值类型
  2. 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'
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值