DIV CSS 佈局教程網

淺談 JavaScript 的資料型別判斷
編輯:JavaScript基礎知識     

前言

平常要判斷型別時,總是順手抄起 typeof 就像拔槍一樣突突突,卻很少停下來細究它的實際行為。於是趁著空檔,特別做了一次較為完整的梳理。

先來把 typeof 的檢測結果通盤看一遍。這裡準備了一組涵蓋面較廣的變數:

 var s = new String('abc'), n = 123, b = true, a = new Array(), o = new Object(), d = new Date(), u = undefined, f = function(){}, w = window, doc = document, r = new RegExp(), m = Math, t = window.setTimeout, _s = '123', _n = null, _d = document.body, _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 最多只能辨識五種型別:string、number、boolean、undefined、object。實際上 JavaScript 也只有這五種資料型別。

像 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 兩種方式結合起來,就能自己寫出一個更精準的型別檢測方法:

 function getType(){ var value = arguments[0], type = function(){ return /\w+\s(\w+)\(\)\s.+?/.test(value.constructor.toString()) ? RegExp.$1.toLowerCase() : 'arguments except'; }; if(typeof value){ return value !== null ? value !== undefined ? type() : 'undefined' : 'null'; }else{ return 'undefined'; } }

另外,typeof 在使用上還藏著一個小技巧:用它去檢測一個根本不存在的「變數」時並不會報錯,而是回傳 undefined。回想以前,面對不確定的程式碼,我們往往得靠 try{}catch(e){...} 來試著執行。

最後,在查閱 typeof 資料時,也順手看了下 instanceof 運算子。簡單來說,instanceof 用來「檢測左側參數是否為右側參數的一個實例」,是則回傳 true,否則回傳 false。示例:

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

這裡因為 p 是建構函式 person 的一個實例,透過 instanceof 得到的自然是 true。這一點也可以從 p.constructor == 'function person(){}' 得到印證。

再稍微複雜一些的情況:

 function person(){} function animal(){} persion.prototype = new animal(); var p = new person(); p instanceof persion() //--> true p instanceof animal() //--> true

好了,關於型別判斷就先聊到這兒。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved