浅玩JavaScript的数据类型判断

前言

平常在需要进行类型判断时,随手拿起typeof就像手枪一样只管突突突...也没有仔细的去了解它的具体特性。
所以这里就利用空闲时间,来做一个较为详细的了解。

首先我们来全面看一遍typeof类型的检测情况:

这里我给一组比较详细的数据类型变量:

 1     var s = new String('abc'),
 2         n = 123,
 3         b = true,
 4         a = new Array(),
 5         o = new Object(),
 6         d = new Date(),
 7         u = undefined,
 8         f = function(){},
 9         w = window,
10         doc = document,
11         r = new RegExp(),
12         m = Math,
13         t = window.setTimeout,
14         _s = '123',
15         _n = null,
16         _d = document.body,
17         _nan = NaN;

下面我们用typeof分别来检测这些变量的数据类型,看看具体的返回结果:

	typeof s --> string
	typeof n --> number
	typeof b --> boolean
	typeof a --> object
	typeof o --> object
	typeof d --> object
	typeof u --> undefined
	typeof f --> function
	typeof w --> object
	typeof doc --> object
	typeof r --> object
	typeof m --> object
	typoef t --> function
	typeof _s --> number
	typoef _n --> object
	typeof _d --> object
	typeof _nan --> number

通过以上测试,可以很肯定的说typeof最多只可检查5种数据类型:  string,number,boolean,underfined,object  。
实际上JavaScript也只有这5种数据类型。
像Date、Array、Function、HTMLElement、Math、RegExp这些数据,在JavaScript中,他们都是Object对象的再次包装,所以用typeof检测它们就会返回 object 类型。
但是在实际的运用中,如果将 Date、Array、Function、HTMLElement、Math、RegExp 都作为object类型看待,就很不切实际。
幸运的是,我们可以从这些对象的构造函数(constructor)上获得到代表它们具体的含义的信息。

例如: 

a.constructor.toString() -- > "function Array() { [native code] }";

所以通过结合typeof、Object.constructor 这两种方法,自己编写了一个检测类型的方法:

 1 function getType(){
 2 
 3     var value = arguments[0],
 4         type = function(){
 5             return /\w+\s(\w+)\(\)\s.+?/.test(value.constructor.toString()) ? RegExp.$1.toLowerCase() : 'arguments except'; 
 6         };
 7 
 8     if(typeof value){
 9         return value !== null ?  value !== undefined ? type() : 'undefined' :  'null';
10     }else{
11         return 'undefined';
12     }
13 
14 }

另外对于typeof在使用上还有一个小技巧。用typeof检测一个不存在“变量”的数据类型时,并不会报错,而是返回undefined。
而在以前,对与不确定的代码,我们都是通过try{}catch(e){...} 进行尝试运行的。

最后在查阅typeof的资料时。顺便也简单的看了下 instanceof 运算符的介绍。
总的来说,instanceof运算符是用于“检测左侧参数是否是右侧参数的一个实例”。如果是,则返回true,否则返回false
示例:

1 var p = new person();
2 p instanceof person // --> true;

在这个示例中因为p是构造函数的person的一个实例,所以通过instanceof运算符得到的就是true。
这一点,可以在 p.constructor == 'function person(){}'  得到应征。
再稍微复杂的还有:

1 function person(){}
2 function animal(){}
3 
4 persion.prototype = new animal();
5 var p = new person();
6 p instanceof persion() //--> true
7 p instanceof animal() //--> true

 

---------------- 好了... 睡觉去.... --------- 明天继续奋斗!!!! ---------------

posted @ 2016-11-05 00:54  卷柏的花期  阅读(596)  评论(1编辑  收藏  举报