JS类型检测

一、js类型分类

js中数据类型可分为两大类:

  • 原始类型:Number、String、Boolean、Null、Undefined
  • 对象类型:Function、Array、Date等

二、 类型检测

1、typeof运算符

适合基本类型及function检测,遇到null失效

typeof null==="object"
typeof new Object()==="object"
typeof [1,2]==="object"

typeof  100==="number"
typeof  NaN==="number"

typeof undefined==="undefined"
typeof function==="function"
typeof true==="boolean"
typeof "hello"==="string"

2、instanceof操作符

适合自定义对象,也可以用来检测原生对象,在不同iframe和window间检测时失效。

3、Object.prototype.toString方法

通过{}.toString拿到,适合内置对象和基元类型,遇到null和undefined失效。

Object.prototype.toString.apply([])==="[object Array"
Object.prototype.toString.apply(function(){})==="[object Function]"
Object.prototype.toString.apply(null)==="[object Null]"
Object.prototype.toString.apply(undefined)==="[object Undefined]"

你可能感兴趣的:(JS类型检测)