前言:
最近在做一个项目,碰到一些需要进行数据类型判断的地方,索性就总结一下所有JS检测类型的方法。
先介绍一下JS的数据类型
JS分基础数据类型和复杂数据类型,也叫引用数据类型
基础数据类型:
Sting Number Boolean Null Undefined ,以及es6新增的一个Symbol
复杂数据类型:
Object 其中包括 Arry,Function,RegExp,Date
判断方法:
- typeof
- instanceof
- constructor
- Object.prototype.toString.call(obj)
用法
typeof
typeof用来检测基础类型 ,返回类型的字符串
//字符串
typeof 'leon' // 'sting'
//整数
typeof 22 // 'number'
//undefined
typeof undefined // 'undefined'
//Boolean
typeof true // 'boolean'
//Null
typeof null // 'object' 这为什么是object ?
// 因为null表示的是一个空指针,指针表示的是引用型数据,所以返回object
//Object
typeof [1,2.3] //'object'
typeof {a: 'ww'} //'object'
typeof new Date() //'object'
//function
typeof function(){} //"function"
instanceof
instanceof 用来检测复杂类型,返回boolean,但是不能检测Null
// 这种检测方式一般不常用
[1, 2] instanceof Array //true
({a: 1}) instanceof Object //true
(function(){}) instanceof Function //true
Constructor
返回结果为构造器,也可以检测自定义类型;
但是不适用于null和undefined。
[1,2,3].constructor == Arry //true
(function(){}).constructor == Function // true
{ 'name':'aaa'}.constructor == Object // true
(1234).constructor == Number // true
(true).constructor == Boolean // true
function Leon(){}
var leon = new Leon();
leon.constructor == Leon; // true
Object.prototype.toString.call(obj)
这种方法是用的最多的也是最万能的,推荐使用
Object.prototype.toString.call('aaa'); //[object,String]
Object.prototype.toString.call(1); //[object,Number]
Object.prototype.toString.call(true) // [object,Boolean]
Object.prototype.toString.call([1,2,3]); //"[object Array]"
Object.prototype.toString.call({name:'leon'}); //"[object Object]"
Object.prototype.toString.call(function(){}); //"[object Function]"
Object.prototype.toString.call(null); //"[object Null]"
Object.prototype.toString.call(undefined); //"[object Undefined]"