自己实现的typeOf函数1

自己实现的typeOf函数:返回传入参数的类型

主要用于解决,js自带的typeof返回结果不精确;Ext JS中typeOf对字符串对象、元素节点、文本节点、空白文本节点判断并不准确的问题

js代码如下:

 1 /**
 2   返回传入参数的类型
 3 */
 4 function typeOf(value){
 5   //数据类型判断
 6   if(value===null){
 7     return 'null';
 8   }
 9   //数据类型判断
10   var type = typeof value;
11   if(type=='undefined'||type=='string'||type=='number'||
12      type=='boolean'||type=='function'){
13      return type;
14   }
15   //数据类型判断
16   var stringType = Object.prototype.toString.call(value);
17   switch(stringType){
18     case "[object String]":  return 'string';
19     case "[object Number]":  return 'number';
20     case "[object Boolean]": return 'boolean';
21     case "[object Date]":    return 'date';
22     case "[object Array]":   return 'array';
23     case "[object RegExp]":  return 'regexp';
24     case "[object Object]":  return 'object';
25   }
26   //节点类型判断(可扩展)
27   var nodeType = value.nodeType;
28   if(nodeType!='undefined'){
29     if(nodeType==1){//元素节点
30       return 'element';
31     }
32     if(nodeType==2){//属性节点
33       return 'attribute';
34     }
35     if(nodeType==3){//文本节点
36        if(/\S/.test(value.nodeValue)){//节点值包含非空白字符
37          return 'textnode';//非空白文本节点
38        }
39        return 'whitespace'//空白文本节点
40     }
41   }
42   //其它的统一识别为'object'
43   return type;//'object'
44 }

测试HTML代码如下:

 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 2         "http://www.w3.org/TR/html4/loose.dtd">
 3 <html>
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>typeof</title>
 7     <script type="text/javascript" src="./js/TypeOf0.js"></script>
 8     <script type="text/javascript">
 9         window.onload = _pageLoaded;
10 
11         /**
12          * 页面加载完毕后执行的函数
13          * @private
14          */
15         function _pageLoaded(){
16           console.info(typeOf(new String('123')));
17           console.info(typeOf(function(){}));
18           console.info(typeOf(document.getElementById('table1')));
19           console.info(typeOf(document.getElementById('table1').getAttributeNode('id')));
20           console.info(typeOf(document.getElementById('node1').firstChild));
21           console.info(typeOf(document.getElementById('node2').firstChild));
22           var obj = {name:'pine'};
23           console.info(typeOf(obj));
24           console.info(typeOf(document));
25           var _obj = {nodeType:1};
26           console.info(typeOf(_obj));
27         }
28     </script>
29 </head>
30 <body>
31 <table id="table1">
32     <tr>
33         <td>1</td>
34         <td>2</td>
35     </tr>
36     <tr>
37         <td>3</td>
38         <td>4</td>
39     </tr>
40 </table>
41 <span id="node1">测试文本~~~</span>
42 <span id="node2">  </span>
43 </body>
44 </html>

 

posted @ 2019-04-22 15:28  松松敲代码  阅读(684)  评论(0编辑  收藏  举报