巧用 Object.prototype.toString 判断对象类型

有时候我们需要判断一个 JavaScript 对象的类型,常用的方法是运算符 typeof,比如:

typeof null
// "object"
typeof []
// "object"
typeof 3
// "number"
typeof true
// "boolean"
typeof JSON.parse
// "function"

但它有个局限性,就是只能判断一些基本类型,更具体的类型就无法区分了,比如上面的 null 和 [],类型都是 object。怎么办呢?Object 原型上有个 toString 方法,它可以返回对象的类型名字,我们可以通过它来判断具体类型。来看下面的这些例子:


Object.prototype.toString.call([])
// "[object Array]"
Object.prototype.toString.call(function(){})
// "[object Function]"
Object.prototype.toString.call({})
// "[object Object]"
Object.prototype.toString.call(null)
// "[object Null]"
Object.prototype.toString.call(undefined)
// "[object Undefined]"
Object.prototype.toString.call(true)
// "[object Boolean]"
Object.prototype.toString.call('')
// "[object String]"
Object.prototype.toString.call(1.2)
// "[object Number]"
Object.prototype.toString.call(NaN)
// "[object Number]"
Object.prototype.toString.call(Infinity)
// "[object Number]"
Object.prototype.toString.call(/./g)
// "[object RegExp]"
Object.prototype.toString.call()
// "[object Undefined]"
Object.prototype.toString.call(void 0)
// "[object Undefined]"

Object.prototype.toString.call(window)
// "[object global]"
Object.prototype.toString.call(document)
// "[object HTMLDocument]"
Object.prototype.toString.call(document.location)
// "[object Location]"
Object.prototype.toString.call(document.location.href)
// "[object String]"

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

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

Object.prototype.toString.call(Math)
// "[object Math]"
Object.prototype.toString.call(Math.abs)
// "[object Function]"

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

Object.prototype.toString.call(JSON)
// "[object JSON]"
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容