本文正式地址:http://www.xiabingbao.com/javascript/2015/07/04/javascript-typejavascript
在JavaScript中,有5種基本數據類型和1種複雜數據類型,基本數據類型有:Undefined, Null, Boolean, Number和String;複雜數據類型是Object,Object
中還細分了不少具體的類型,好比:Array, Function, Date等等。今天咱們就來探討一下,使用什麼方法判斷一個出一個變量的類型。java
在講解各類方法以前,咱們首先定義出幾個測試變量,看看後面的方法究竟能把變量的類型解析成什麼樣子,如下幾個變量差很少包含了咱們在實際編碼中經常使用的類型。jquery
var num = 123; var str = 'abcdef'; var bool = true; var arr = [1, 2, 3, 4]; var json = {name:'wenzi', age:25}; var func = function(){ console.log('this is function'); } var und = undefined; var nul = null; var date = new Date(); var reg = /^[a-zA-Z]{5,20}$/; var error= new Error();
咱們平時用的最多的就是用typeof
檢測變量類型了。此次,咱們也使用typeof
檢測變量的類型:json
console.log( typeof num, typeof str, typeof bool, typeof arr, typeof json, typeof func, typeof und, typeof nul, typeof date, typeof reg, typeof error ); // 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
。框架
在 JavaScript 中,判斷一個變量的類型嚐嚐會用 typeof 運算符,在使用 typeof 運算符時採用引用類型存儲值會出現一個問題,不管引用的是什麼類型的對象,它都返回 "object"。ECMAScript 引入了另外一個 Java 運算符 instanceof 來解決這個問題。instanceof 運算符與 typeof 運算符類似,用於識別正在處理的對象的類型。與 typeof 方法不一樣的是,instanceof 方法要求開發者明確地確認對象爲某特定類型。例如:函數
function Person(){ } var Tom = new Person(); console.log(Tom instanceof Person); // true
咱們再看看下面的例子:測試
function Person(){ } function Student(){ } Student.prototype = new Person(); var John = new Student(); console.log(John instanceof Student); // true console.log(John instancdof Person); // true
instanceof
還能檢測出多層繼承的關係。this
好了,咱們來使用instanceof
檢測上面的那些變量:編碼
console.log( num instanceof Number, str instanceof String, bool instanceof Boolean, arr instanceof Array, json instanceof Object, func instanceof Function, und instanceof Object, nul instanceof Object, date instanceof Date, reg instanceof RegExp, error instanceof Error ) // num : false // str : false // bool : false // arr : true // json : true // func : true // und : false // nul : false // date : true // reg : true // error : true
從上面的運行結果咱們能夠看到,num, str和bool沒有檢測出他的類型,可是咱們使用下面的方式建立num,是能夠檢測出類型的:
var num = new Number(123); var str = new String('abcdef'); var boolean = new Boolean(true);
同時,咱們也要看到,und和nul是檢測的Object類型,才輸出的true,由於js中沒有Undefined
和Null
的這種全局類型,他們und和nul都屬於Object類型,所以輸出了true。
在使用instanceof
檢測變量類型時,咱們是檢測不到number
, 'string', bool
的類型的。所以,咱們須要換一種方式來解決這個問題。
constructor原本是原型對象上的屬性,指向構造函數。可是根據實例對象尋找屬性的順序,若實例對象上沒有實例屬性或方法時,就去原型鏈上尋找,所以,實例對象也是能使用constructor屬性的。
咱們先來輸出一下num.constructor
的內容,即數字類型的變量的構造函數是什麼樣子的:
function Number() { [native code] }
咱們能夠看到它指向了Number
的構造函數,所以,咱們可使用num.constructor==Number
來判斷num是否是Number類型的,其餘的變量也相似:
function Person(){ } var Tom = new Person(); // undefined和null沒有constructor屬性 console.log( Tom.constructor==Person, num.constructor==Number, str.constructor==String, bool.constructor==Boolean, arr.constructor==Array, json.constructor==Object, func.constructor==Function, date.constructor==Date, reg.constructor==RegExp, error.constructor==Error ); // 全部結果均爲true
從輸出的結果咱們能夠看出,除了undefined和null,其餘類型的變量均能使用constructor
判斷出類型。
不過使用constructor也不是保險的,由於constructor屬性是能夠被修改的,會致使檢測出的結果不正確,例如:
function Person(){ } function Student(){ } Student.prototype = new Person(); var John = new Student(); console.log(John.constructor==Student); // false console.log(John.constructor==Person); // true
在上面的例子中,Student原型中的constructor被修改成指向到Person,致使檢測不出實例對象John真實的構造函數。
同時,使用instaceof和construcor,被判斷的array必須是在當前頁面聲明的!好比,一個頁面(父頁面)有一個框架,框架中引用了一個頁面(子頁面),在子頁面中聲明瞭一個array,並將其賦值給父頁面的一個變量,這時判斷該變量,Array == object.constructor;會返回false;
緣由:
一、array屬於引用型數據,在傳遞過程當中,僅僅是引用地址的傳遞。
二、每一個頁面的Array原生對象所引用的地址是不同的,在子頁面聲明的array,所對應的構造函數,是子頁面的Array對象;父頁面來進行判斷,使用的Array並不等於子頁面的Array;切記,否則很難跟蹤問題!
咱們先無論這個是什麼,先來看看他是怎麼檢測變量類型的:
console.log( Object.prototype.toString.call(num), Object.prototype.toString.call(str), Object.prototype.toString.call(bool), Object.prototype.toString.call(arr), Object.prototype.toString.call(json), Object.prototype.toString.call(func), Object.prototype.toString.call(und), Object.prototype.toString.call(nul), Object.prototype.toString.call(date), Object.prototype.toString.call(reg), Object.prototype.toString.call(error) ); // '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]' // '[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
的:
Object.prototype.toString( ) When the toString method is called, the following steps are taken:
- Get the [[Class]] property of this object.
- Compute a string value by concatenating the three strings 「[object 「, Result (1), and 「]」.
- Return Result (2)
上面的規範定義了Object.prototype.toString的行爲:首先,取得對象的一個內部屬性[[Class]],而後依據這個屬性,返回一個相似於"[object Array]"的字符串做爲結果(看過ECMA標準的應該都知道,[[]]用來表示語言內部用到的、外部不可直接訪問的屬性,稱爲「內部屬性」)。利用這個方法,再配合call,咱們能夠取得任何對象的內部屬性[[Class]],而後把類型檢測轉化爲字符串比較,以達到咱們的目的。
在jquery中提供了一個$.type
的接口,來讓咱們檢測變量的類型:
console.log( $.type(num), $.type(str), $.type(bool), $.type(arr), $.type(json), $.type(func), $.type(und), $.type(nul), $.type(date), $.type(reg), $.type(error) ); // 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方法的:
// 實例對象是能直接使用原型鏈上的方法的 var class2type = {}; var toString = class2type.toString; // 省略部分代碼... type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android<4.0, iOS<6 (functionish RegExp) return (typeof obj === "object" || typeof obj === "function") ? (class2type[ toString.call(obj) ] || "object") : typeof obj; }, // 省略部分代碼... // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); });
咱們先來看看jQuery.each的這部分:
// Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); //循環以後,`class2type`的值是: class2type = { '[object Boolean]' : 'boolean', '[object Number]' : 'number', '[object String]' : 'string', '[object Function]': 'function', '[object Array]' : 'array', '[object Date]' : 'date', '[object RegExp]' : 'regExp', '[object Object]' : 'object', '[object Error]' : 'error' }
再來看看type
方法:
// type的實現 type: function( obj ) { // 若傳入的是null或undefined,則直接返回這個對象的字符串 // 即若傳入的對象obj是undefined,則返回"undefined" if ( obj == null ) { return obj + ""; } // Support: Android<4.0, iOS<6 (functionish RegExp) // 低版本regExp返回function類型;高版本已修正,返回object類型 // 若使用typeof檢測出的obj類型是object或function,則返回class2type的值,不然返回typeof檢測的類型 return (typeof obj === "object" || typeof obj === "function") ? (class2type[ toString.call(obj) ] || "object") : typeof obj; }
當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便可。
本文正式地址:http://www.xiabingbao.com/javascript/2015/07/04/javascript-type