JavaScript中的typeof
js中的 typeof 操作符返回一个字符串,表示未经计算的操作数的类型。
其中null、字符串对象、数字对象、布尔对象、日期、数组、正则返回结果都为object,可见typeof返回结果并不精确
测试代码如下:
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"> 8 window.onload = _pageLoaded; 9 10 /** 11 * 页面加载完毕后执行的函数 12 * @private 13 */ 14 function _pageLoaded(){ 15 function _fn() { 16 } 17 var obj = {name:'pine',age:28}; 18 var arr = [1,2,3]; 19 var reg = /^123$/; 20 var element = document.getElementById('table1');//元素节点 21 var node1 = document.getElementById('node1').firstChild;//文本节点 22 var node2 = document.getElementById('node2').firstChild;//空的文本节点 23 24 console.info(" typeof undefined:%s",typeof undefined); 25 console.info("*typeof null:%s",typeof null); 26 27 console.info(" typeof 字符串:%s",typeof '123'); 28 console.info(" typeof 数字:%s",typeof 123); 29 console.info(" typeof 布尔:%s",typeof true); 30 console.info("*typeof 字符串对象:%s",typeof new String('123')); 31 console.info("*typeof 数字对象:%s",typeof new Number(123)); 32 console.info("*typeof 布尔对象:%s",typeof new Boolean(true)); 33 34 console.info("*typeof 日期:%s",typeof new Date()); 35 console.info(" typeof 函数:%s",typeof _fn); 36 console.info(" typeof 对象:%s",typeof obj); 37 console.info("*typeof 数组:%s",typeof arr); 38 console.info("*typeof 正则:%s",typeof reg); 39 40 console.info(" typeof dom元素:%s",typeof element); 41 console.info(" typeof dom文本节点:%s",typeof node1); 42 console.info(" typeof 空的dom文本节点:%s",typeof node2); 43 44 } 45 </script> 46 </head> 47 <body> 48 <table id="table1"> 49 <tr> 50 <td>1</td> 51 <td>2</td> 52 </tr> 53 <tr> 54 <td>3</td> 55 <td>4</td> 56 </tr> 57 </table> 58 <span id="node1">测试文本~~~</span> 59 <span id="node2"> </span> 60 </body> 61 </html>