如何检测对象类型

检测数据类型第一个想到的肯定是typeof方法,但是typeof返回的是“String“、“Number“、"boolean"、"undefined"、"object"、"function"、"symbol"几个值。

对于数组和null返回的也是object。

今天学习一种新的判断类型的方式:Object.prototype.toString.call(value) || Object.prototype.toString.apply(value)

Object.prototype.toString.call(new Date); // [object Date]
Object.prototype.toString.call(new String); // [object String]
Object.prototype.toString.call(Math); // [object Math]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(new Objcet) //[object Object]
Object.prototype.toString.call(new RegExp) //[object RegExp]

 

posted @ 2019-03-22 13:56  前端守望者  阅读(601)  评论(0编辑  收藏  举报