数据检测类型

数据检测类型

经常会遇到检测数据类型的问题,这里归纳总结一下。

检测类型

1.typeof

常用于检测基本数据类型,但是 null 和 Array 类型不起作用,会返回 Object

typeof undefined		//undefined
typeof null				//object
typeof true				//boolean
tyoeof ''				//string
typeof []				//object
typeof function(){}		//function
typeof {}				//object

2.Object.prototype.toString.call()

每种内置对象都定义了 [[Class]] 内部属性的值,用于内部区分对象的种类,我们不能直接访问这个属性,但是我们可以通过一种方法访问,Object.prototype.toString.call

Object.prototype.toString.call(null)
//'[object Null]'

Object.prototype.toString.call(undefined)
//'[object Undefined]'

Object.prototype.toString.call(Math)
//'[object Math]'

Object.prototype.toString.call({})
//'[object Object]'

Object.prototype.toString.call([])
//'[object Array]'

Object.prototype.toString.call(new Date)
//"[object Date]"

常用于检测引用类型,该属性是不可更改的,所以十分可靠

实例:

function getType(val){
	let reg = /(\b\w*)]$/;
	let res = Object.prototype.toString.call(val);
	return reg.exec(res) && reg.exec(res)[1];
}

getType(new Date()) === 'Date'		//true
getType(new RegExp()) === 'RegExp'	//true

检测实例

3.constructor

可更改的属性,十分不可靠

4.instanceof

常用于判断是否是某个对象的实例。

  • 不能判断 null 和 undefined(会报错)

  • 用对象字面量创建的基本数据类型不属于对象类型

      1 instanceof Number		//false
      '' instanceof String	//false
      
      new Number(1) instanceof Number		//true
      new String('') instanceof String	//true
    

在 child instanceof super 中,实质是判断 super.prototype 是否在 child 的原型链上(这样判断实例并完全不可靠)。

5.isPrototypeOf

ES 6 检测一个对象是否是另一个对象的原型,可用于判断是否是某个对象的实例,十分可靠。

super.isPrototypeOf(child)

检测空对象

1.JSON.stringify(data) == “{}”

2.Object.keys(obj).length == 0

3.Object.getOwnPropertyNames(obj).length == 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值