js中的數據類型檢測


js中的數據類型檢測常用的方法是使用typeof,typeof運算符會返回下列6中類型之一:

  • "number"
  • "string"
  • "boolean"
  • "object"
  • "function"
  • "undefined"

例如:

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <script type="text/javascript">
 7         var a="a";
 8         var b=2;
 9         var c=undefined;
10         var d=null;
11         var e={};
12         function f(){
13             return true;
14         }
15         console.log(typeof(a));
16         console.log(typeof(b));
17         console.log(typeof(c));
18         console.log(typeof(d));
19         console.log(typeof(e));
20         console.log(typeof(f));    
21     </script>
22 </head>
23 <body>
24     
25 </body>
26 </html>

結果如下:

從結果中可以看出使用typeof檢測null值時,返回的是object,而不是null。這樣其實並不能真正的檢測出數據類型。可以向下面定義一個方法檢測出null類型。

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <script type="text/javascript">
 7         var a="a";
 8         var b=2;
 9         var c=undefined;
10         var d=null;
11         var e={};
12         function f(){
13             return true;
14         }
15         function type(o){
16             console.log((o===null)?"null":(typeof(o)));
17         }
18         type(a);
19         type(b);
20         type(c);
21         type(d);
22         type(e);
23         type(f);
24     </script>
25 </head>
26 <body>
27     
28 </body>
29 </html>

 得到的結果如下:

 

而對於復雜的數據類型,比如對象或者數組,可以使用constructor屬性。constructor屬性可以判斷絕大部分數據的類型,但是對undefined和null類型並不適用,因為javascript解釋器會拋出異常。

數值直面量也不能使用constructor屬性,可以加上一個小括號,將數值轉化為對象,例如:

 alert((1).constructor); 

 

對於內置對象,使用toString()方法檢測對象類型時最安全、最准確的。調用toString()方法把對象轉化為字符串,然后通過檢測字符串中是否包含數組所特有的標志字符可以確定對象的類型。

例如:

 1 function typeof(o){
 2       var _toString=Object.prototype.toString;
 3       var _type={
 4                  "undefined":"undefined",
 5                  "number":"number",
 6                  "boolean":"boolean",
 7                  "string":"string",
 8                  "[object Function]":"function",
 9                  "[object Array]":"array",
10                  "[object RegExp]":"regexp",
11                  "[object Date]":"date",
12                  "[object Erroe]":"error"
13         }
14         return _type[typeof o]||_type[_toString.call(o)]||(o?"object":"null");
15 }
16                   

 對於非內置對象,只能使用constructor屬性和instanceof運算符來實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM