自己实现的TypeOf函数2

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

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

与上一篇的主要区别是:将前2个数据类型判断统一合并到第3个数据类型判断里面

js代码如下:

 

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

测试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/TypeOf1.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:36  松松敲代码  阅读(533)  评论(0编辑  收藏  举报