*本文章主要总结一下js数据类型的识别判断方法
tyoeof
instanceof
Object.prototype.toString.call
constructor
最后封装一个函数,能够判别全部的类型*javascript
基本类型:java
undefined(小写)
,在使用var声明变量可是未对其加以初始化时,这个变量的值就是undefined。null(小写)
,null值表示一个空对象指针,因此用typeof操做符检测null值会返回object的缘由。true和false(小写)
。引用类型数组
首先typeof不是方法,只是一个操做符。函数
Null除外
)Function除外
)返回的值首字母都是小写
!!!!!!!!//识别标准类型 typeof "jerry"; //"string" typeof 12; //"number" typeof true; //"boolean" typeof undefined; //"undefined" typeof null; //"object" typeof {name:"jerry"}; //"object" //识别引用类型 typeof function(){}; //"function" typeof []; //"object" typeof new Date; //"object" typeof /\d/; //"object" //建立一个自定义对象 function Person(){}; typeof new Person; //"object"
//可以判别引用类型 [] instanceof Array; //true /\d/ instanceof RegExp; //true new Date instanceof Date; //true var a = function(){}; a instanceof Function; //true //不能判别原始类型 1 instanceof Number; //false "jerry" instanceof String; //false //可以判别自定义对象类型及父子类型 //自定义类型 function Person(){}; Person instanceof Function; //true //父子类型 function Point(x,y){ this.x = x; this.y = y; } function Cirele(x,y,r){ Point.call(this,x,y); this.radius = r; } Circle.prototype = new Point(); Circle.prototype.constructor = Circle; var c = new Circle(1,1,2); c instanceof Circle //true c instanceof Point //true
结论
:测试
Object.prototype.toString.call("123"); //"[object String]" //封装函数,并作截取 function type(obj){ return Object.prototype.toString.call(obj).slice(8,-1); } //测试 type("123"); //"String" //自定义类型 function Point(x,y){ this.x = x; this.y = y; } //测试 type(new Point(1,2)); //"Object"
结论:this
//判断基本类型(基本类型也有构造函数);可是null和undefined除外,它俩没有构造函数 "jerry".constructor === String; //true (1).constructor ===Number; //true //判断引用类型 new Date().constructor === Date; //true [].constructor === Array; //true //判断自定义对象 function Person(name){ this.name = name; } new Person("jerry").constructor === Person; //true //对constructor判别进行方法的封装 function getConstructorName(obj){ return (obj===undefined||obj===null)?obj: (obj.constructor && obj.constructor.toString().match(/function\s*([^(]*)/)[1]); }
封装的原理:prototype
math(/function\s*([^(]*)/)[1]
:匹配构造函数的名称,正则匹配结论:指针
结论:因此能够封装一个函数getConstructorName判断全部类型,可是这个函数返回的除了null和undefined是小写以外,其余的首字母都是大写。code