js中如何判断类型

165 阅读1分钟

一、 类型包含哪些

1.基本类型: Undefined、Null、String、Boolean、Number

2.引用类型:RegExp、Date、原始值包装类型(Boolean、Number、String)、Object、Array、Error、Function

自动创建的原始值包装类型的对象,只存在于代码执行期间,意味着不能在运行时给原始值添加属性和方法,这条语句执行完实例就销毁了

二、typeof方式

通过typeof关键字,返回类型为字符串

1. 未定义的值或者变量------------------------------'undefined'

2. 布尔类型的值或者变量 ---------------------------'boolean'

3. 字符串类型的值或者变量--------------------------'string'

4. 数字类型的值或者变量-----------------------------‘number’

5. 对象类型、数组类型的值或者变量;null ------------'object'

6. 函数类型的值或者变量------------------------------‘function’

注: typeof null   === 'object' 

       typeof NaN === 'number'    

       typeof (String('a')) === 'object'  

       typeof(Date()) === 'object'   因此对于具体判断某个变量是否某个对象的实例不能准确的判断

三、 instanceof方式

A instanceof B 从A原型链__proto__上查找是否存在B

[] instanceof Array    ------------------------true

[] instanceof Object -------------------------true

因此当深层次查找原型链上的内容导致不能精确判断为具体为哪种类型

四、toString方式

Object.prototype.toString.call(null)  -------------------- "[object Null]"
Object.prototype.toString.call(undefined) -------------- "[object Undefined]"
Object.prototype.toString.call('aa') ----------------------"[object String]"
Object.prototype.toString.call(true)----------------------"[object Boolean]"
Object.prototype.toString.call(new Error()) --------------"[object Error]"
Object.prototype.toString.call(function(){})--------------"[object Function]"
Object.prototype.toString.call([]) ------------------------- "[object Array]"

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

Object.prototype.toString.call(new RegExp()) ---------------"[object RegExp]"