总结js数据类型的辨认判断办法
tyoeof
instanceof
Object.prototype.toString.call
constructor
最初封装一个函数,能够判断所有的类型*
1.数据类型
根本类型:
Undefined类型:该类型只有一个值,即undefined(小写),在应用var申明变量然而未对其加以初始化时,这个变量的值就是undefined。
Null类型:该类型也只有一个值,即null(小写),null值示意一个空对象指针,所以用typeof操作符检测null值会返回object的起因。
Boolean类型:改类型有两个值:true和false(小写)。
Number类型:示意整数和浮点数
String类型:即字符串
援用类型
Object类型:即对象
Array类型:数组
Date类型:日期
RegExp类型:正则
Function类型
2.类型的辨认的判断办法
(1)typeof总结:
首先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"
(2)instanceof
//可能判断援用类型[] instanceof Array; //true/\d/ instanceof RegExp; //truenew Date instanceof Date; //truevar 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 //truec instanceof Point //true
论断:
能够判断内置对象类型
不能判断原始类型
判断自定义对象类型
联合1和3,用instanceof能够辨认所有的对象类型
(3)Object.prototype.toString.call
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"
论断:
上述封装的函数能够辨认根本类型以及援用对象类型
不能辨认自定义对象类型
(4)constructor(结构这个对象的构造函数的自身)
//判断根本类型(根本类型也有构造函数);然而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]);}
封装的原理:
obj:如果传入的参数是null或者undefined,没有构造函数间接返回
obj.constructor如果存在执行&&前面的语句
obj.constructor.toString():将类型对应的构造函数转化成字符串 "Function Number(){code...}"
math(/function\s(1)/)[1]:匹配构造函数的名称,正则匹配
论断:
判断根本类型(Undefined/Null除外)
判断援用类型
判断自定义对象类型
论断:所以能够封装一个函数getConstructorName判断所有类型,然而这个函数返回的除了null和undefined是小写之外,其余的首字母都是大写。
- ( ↩