js判断数据类型

我们有几种方式判断

1、typeof

console.log(typeof 123)   // number
console.log(typeof 'java') // string
console.log(typeof true)  // boolean
console.log(typeof undefined)  //undefined
console.log(typeof null)	// object
console.log(typeof [1,2,3]) //object
console.log(typeof {name:'kebi'}) //object
console.log(typeof function(){}) // function
uconsole.log(typeof /[0-9]/) // object

通过控制台打印,我们可以看出typeof判断数据类型,Null、Array、Object、RegExp判断都是object
判断 Number、String、Boolean、Undefined、Function类型可以用typeof方法

2、instanceof

我们可以用instanceof,instanceof运算符需要指定一个构造函数,或者说指定数据的一种类型,用来判断构造函数的原型是否在给定对象的原型链上

console.log(123 instanceof Number)   // false
console.log('123' instanceof String) // false
console.log(true instanceof Boolean) // false
console.log(null instanceof Object) // false
console.log(undefined instanceof Object) // false
console.log([1,2,3] instanceof Array)  // true
console.log({name:'123'} instanceof Object) // true
console.log(new Date() instanceof Date) // true
console.log(/[0-9]/ instanceof RegExp) // true

Number、String、Boolean判断不出他们的类型
null、undefined也返回了false,那是因为他们的类型就是他们本身,并不是Object创建出来它们

3、toString

为了让每个对象都可以通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用

 let tostring = Object.prototype.toString
 console.log(tostring.call(123)) 	//[object Number]
console.log(tostring.call('123'))   //[object String]
console.log(tostring.call(true))    //[object Boolean]
console.log(tostring.call(undefined)) //[object Undefined]
console.log(tostring.call(null))    //[object Null]
console.log(tostring.call([1,2,3])) //[object Array]
console.log(tostring.call({name:'123'})) //[object Object]
console.log(tostring.call(new Date())) //[object Date]

打印出来结果,我们可以看到,数据类型都可以判断出来

我们可以封装一个判断数据类型的函数
function getType(val){
	let type = typeof val
	if(type !== 'object'){
		return type
	}
	//如果不是object类型,我们进一步判断
	type = Object.prototype.toString.call(val)
	return type.replace(/^\[object (\S+)\]$/,$1)
}

getType(123) // number
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值