在JavaScript中,有5種基本數據類型和1種復雜數據類型,基本數據類型有:Undefined, Null, Boolean, Number和String;復雜數據類型是Object,Object中還細分了很多具體的類型,比如:Array, Function, Date等等。今天我們就來探討一下,使用什么方法判斷一個出一個變量的類型。
在講解各種方法之前,我們首先定義出幾個測試變量,看看后面的方法究竟能把變量的類型解析成什么樣子,以下幾個變量差不多包含了我們在實際編碼中常用的類型。
1 var num = 123; 2 var str = 'abcdef'; 3 var bool = true; 4 var arr = [1, 2, 3, 4]; 5 var json = {name:'wenzi', age:25}; 6 var func = function(){ console.log('this is function'); } 7 var und = undefined; 8 var nul = null; 9 var date = new Date(); 10 var reg = /^[a-zA-Z]{5,20}$/; 11 var error= new Error();
1. 使用typeof檢測
我們平時用的最多的就是用typeof檢測變量類型了。這次,我們也使用typeof檢測變量的類型:
1 console.log( 2 typeof num, 3 typeof str, 4 typeof bool, 5 typeof arr, 6 typeof json, 7 typeof func, 8 typeof und, 9 typeof nul, 10 typeof date, 11 typeof reg, 12 typeof error 13 ); 14 // number string boolean object object function undefined object object object object
從輸出的結果來看,arr, json, nul, date, reg, error 全部被檢測為object類型,其他的變量能夠被正確檢測出來。當需要變量是否是number, string, boolean, function, undefined, json類型時,可以使用typeof進行判斷。其他變量是判斷不出類型的,包括null。
還有,typeof是區分不出array和json類型的。因為使用typeof這個變量時,array和json類型輸出的都是object。
2. 使用instance檢測
在 JavaScript 中,判斷一個變量的類型嘗嘗會用 typeof 運算符,在使用 typeof 運算符時采用引用類型存儲值會出現一個問題,無論引用的是什么類型的對象,它都返回 “object”。ECMAScript 引入了另一個 Java 運算符 instanceof 來解決這個問題。instanceof 運算符與 typeof 運算符相似,用於識別正在處理的對象的類型。與 typeof 方法不同的是,instanceof 方法要求開發者明確地確認對象為某特定類型。例如
1 function Person(){ 2 3 } 4 var Tom = new Person(); 5 console.log(Tom instanceof Person); // true
我們再看看下面的例子:
1 function Person(){ 2 3 } 4 function Student(){ 5 6 } 7 Student.prototype = new Person(); 8 var John = new Student(); 9 console.log(John instanceof Student); // true 10 console.log(John instancdof Person); // true
instanceof還能檢測出多層繼承的關系。
好了,我們來使用instanceof檢測上面的那些變量:
1 console.log( 2 num instanceof Number, 3 str instanceof String, 4 bool instanceof Boolean, 5 arr instanceof Array, 6 json instanceof Object, 7 func instanceof Function, 8 und instanceof Object, 9 nul instanceof Object, 10 date instanceof Date, 11 reg instanceof RegExp, 12 error instanceof Error 13 ) 14 // num : false 15 // str : false 16 // bool : false 17 // arr : true 18 // json : true 19 // func : true 20 // und : false 21 // nul : false 22 // date : true 23 // reg : true 24 // error : true
從上面的運行結果我們可以看到,num, str和bool沒有檢測出他的類型,但是我們使用下面的方式創建num,是可以檢測出類型的:
1 var num = new Number(123); 2 var str = new String('abcdef'); 3 var boolean = new Boolean(true);
同時,我們也要看到,und和nul是檢測的Object類型,才輸出的true,因為js中沒有Undefined和Null的這種全局類型,他們und和nul都屬於Object類型,因此輸出了true。
3. 使用constructor檢測
在使用instanceof檢測變量類型時,我們是檢測不到number, ‘string', bool的類型的。因此,我們需要換一種方式來解決這個問題。
constructor本來是原型對象上的屬性,指向構造函數。但是根據實例對象尋找屬性的順序,若實例對象上沒有實例屬性或方法時,就去原型鏈上尋找,因此,實例對象也是能使用constructor屬性的。
我們先來輸出一下num.constructor的內容,即數字類型的變量的構造函數是什么樣子的:
function Number() { [native code] }
我們可以看到它指向了Number的構造函數,因此,我們可以使用num.constructor==Number來判斷num是不是Number類型的,其他的變量也類似:
1 function Person(){ 2 3 } 4 var Tom = new Person(); 5 6 // undefined和null沒有constructor屬性 7 console.log( 8 Tom.constructor==Person, 9 num.constructor==Number, 10 str.constructor==String, 11 bool.constructor==Boolean, 12 arr.constructor==Array, 13 json.constructor==Object, 14 func.constructor==Function, 15 date.constructor==Date, 16 reg.constructor==RegExp, 17 error.constructor==Error 18 ); 19 // 所有結果均為true
從輸出的結果我們可以看出,除了undefined和null,其他類型的變量均能使用constructor判斷出類型。
不過使用constructor也不是保險的,因為constructor屬性是可以被修改的,會導致檢測出的結果不正確,例如:
1 function Person(){ 2 3 } 4 function Student(){ 5 6 } 7 Student.prototype = new Person(); 8 var John = new Student(); 9 console.log(John.constructor==Student); // false 10 console.log(John.constructor==Person); // true
在上面的例子中,Student原型中的constructor被修改為指向到Person,導致檢測不出實例對象John真實的構造函數。
同時,使用instaceof和construcor,被判斷的array必須是在當前頁面聲明的!比如,一個頁面(父頁面)有一個框架,框架中引用了一個頁面(子頁面),在子頁面中聲明了一個array,並將其賦值給父頁面的一個變量,這時判斷該變量,Array == object.constructor;會返回false; 原因:
1、array屬於引用型數據,在傳遞過程中,僅僅是引用地址的傳遞。
2、每個頁面的Array原生對象所引用的地址是不一樣的,在子頁面聲明的array,所對應的構造函數,是子頁面的Array對象;父頁面來進行判斷,使用的Array並不等於子頁面的Array;切記,不然很難跟蹤問題!
4. 使用Object.prototype.toString.call
我們先不管這個是什么,先來看看他是怎么檢測變量類型的:
1 prototype.toString.call(num), 2 Object.prototype.toString.call(str), 3 Object.prototype.toString.call(bool), 4 Object.prototype.toString.call(arr), 5 Object.prototype.toString.call(json), 6 Object.prototype.toString.call(func), 7 Object.prototype.toString.call(und), 8 Object.prototype.toString.call(nul), 9 Object.prototype.toString.call(date), 10 Object.prototype.toString.call(reg), 11 Object.prototype.toString.call(error) 12 ); 13 // '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]' 14 // '[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'
從輸出的結果來看,Object.prototype.toString.call(變量)輸出的是一個字符串,字符串里有一個數組,第一個參數是Object,第二個參數就是這個變量的類型,而且,所有變量的類型都檢測出來了,我們只需要取出第二個參數即可。或者可以使用Object.prototype.toString.call(arr)=="object Array"來檢測變量arr是不是數組。
我們現在再來看看ECMA里是是怎么定義Object.prototype.toString.call的:
1 Object.prototype.toString( ) When the toString method is called, the following steps are taken: 2 Get the [[Class]] property of this object. 3 Compute a string value by concatenating the three strings “[object “, Result (1), and “]”. 4 Return Result (2)
上面的規范定義了Object.prototype.toString的行為:首先,取得對象的一個內部屬性[[Class]],然后依據這個屬性,返回一個類似於”[object Array]”的字符串作為結果(看過ECMA標准的應該都知道,[[]]用來表示語言內部用到的、外部不可直接訪問的屬性,稱為“內部屬性”)。利用這個方法,再配合call,我們可以取得任何對象的內部屬性[[Class]],然后把類型檢測轉化為字符串比較,以達到我們的目的。
5. jquery中$.type的實現
在jquery中提供了一個$.type的接口,來讓我們檢測變量的類型:
1 console.log( 2 $.type(num), 3 $.type(str), 4 $.type(bool), 5 $.type(arr), 6 $.type(json), 7 $.type(func), 8 $.type(und), 9 $.type(nul), 10 $.type(date), 11 $.type(reg), 12 $.type(error) 13 ); 14 // number string boolean array object function undefined null date regexp error
看到輸出結果,有沒有一種熟悉的感覺?對,他就是上面使用Object.prototype.toString.call(變量)輸出的結果的第二個參數呀。
我們這里先來對比一下上面所有方法檢測出的結果,橫排是使用的檢測方法, 豎排是各個變量:
| 類型判斷 | typeof | instanceof | constructor | toString.call | $.type |
| num | number | false | true | [object Number] | number |
| str | string | false | true | [object String] | string |
| bool | boolean | false | true | [object Boolean] | boolean |
| arr | object | true | true | [object Array] | array |
| json | object | true | true | [object Object] | object |
| func | function | true | true | [object Function] | function |
| und | undefined | false | - | [object Undefined] | undefined |
| nul | object | false | - | [object Null] | null |
| date | object | true | true | [object Date] | date |
| reg | object | true | true | [object RegExp] | regexp |
| error | object | true | true | [object Error] | error |
| 優點 | 使用簡單,能直接輸出結果 | 能檢測出復雜的類型 | 基本能檢測出所有的類型 | 檢測出所有的類型 | - |
| 缺點 | 檢測出的類型太少 | 基本類型檢測不出,且不能跨iframe | 不能跨iframe,且constructor易被修改 | IE6下undefined,null均為Object | - |
這樣對比一下,就更能看到各個方法之間的區別了,而且Object.prototype.toString.call和$type輸出的結果真的很像。我們來看看jquery(2.1.2版本)內部是怎么實現$.type方法的:
1 // 實例對象是能直接使用原型鏈上的方法的 2 var class2type = {}; 3 var toString = class2type.toString; 4 5 // 省略部分代碼... 6 7 type: function( obj ) { 8 if ( obj == null ) { 9 return obj + ""; 10 } 11 // Support: Android<4.0, iOS<6 (functionish RegExp) 12 return (typeof obj === "object" || typeof obj === "function") ? 13 (class2type[ toString.call(obj) ] || "object") : 14 typeof obj; 15 }, 16 17 // 省略部分代碼... 18 19 // Populate the class2type map 20 jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { 21 class2type[ "[object " + name + "]" ] = name.toLowerCase(); 22 });
我們先來看看jQuery.each的這部分:
1 // Populate the class2type map 2 jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { 3 class2type[ "[object " + name + "]" ] = name.toLowerCase(); 4 }); 5 6 //循環之后,`class2type`的值是: 7 class2type = { 8 '[object Boolean]' : 'boolean', 9 '[object Number]' : 'number', 10 '[object String]' : 'string', 11 '[object Function]': 'function', 12 '[object Array]' : 'array', 13 '[object Date]' : 'date', 14 '[object RegExp]' : 'regExp', 15 '[object Object]' : 'object', 16 '[object Error]' : 'error' 17 }
再來看看type方法:
1 // type的實現 2 type: function( obj ) { 3 // 若傳入的是null或undefined,則直接返回這個對象的字符串 4 // 即若傳入的對象obj是undefined,則返回"undefined" 5 if ( obj == null ) { 6 return obj + ""; 7 } 8 // Support: Android<4.0, iOS<6 (functionish RegExp) 9 // 低版本regExp返回function類型;高版本已修正,返回object類型 10 // 若使用typeof檢測出的obj類型是object或function,則返回class2type的值,否則返回typeof檢測的類型 11 return (typeof obj === "object" || typeof obj === "function") ? 12 (class2type[ toString.call(obj) ] || "object") : 13 typeof obj; 14 }
當typeof obj === "object" || typeof obj === "function"時,就返回class2type[ toString.call(obj)。到這兒,我們就應該明白為什么Object.prototype.toString.call和$.type那么像了吧,其實jquery中就是用Object.prototype.toString.call實現的,把'[object Boolean]'類型轉成'boolean'類型並返回。若class2type存儲的沒有這個變量的類型,那就返回”object”。
除了”object”和”function”類型,其他的類型則使用typeof進行檢測。即number, string, boolean類型的變量,使用typeof即可。
