数据检测类型
经常会遇到检测数据类型的问题,这里归纳总结一下。
检测类型
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