javascript對象類型判斷

#####1.使用typeof操做符javascript

typeof操做符號的做用是返回一個用於只是其操做對象類型的字符串。語法以下:java

typeof val

val參數做爲一個表達式,表明了javascript中的對象類型或基本數據類型,typeof運算會返回該對象或基本數據類型的字符串描述。jquery

typeof根據操做對象和對應的類型描述字符串,包括如下幾種:正則表達式

<table class="standard-table"> <thead> <tr> <th scope="col">操做對象或基本數據類型</th> <th scope="col">類型描述字符串</th> </tr> </thead> <tbody> <tr> <td>Undefined</td> <td><code>"undefined"</code></td> </tr> <tr> <td>Null</td> <td><code>"object"</code></td> </tr> <tr> <td>Boolean</td> <td><code>"boolean"</code></td> </tr> <tr> <td>Number</td> <td><code>"number"</code></td> </tr> <tr> <td>String</td> <td><code>"string"</code></td> </tr> <tr> <td>Function</td> <td><code>"function"</code></td> </tr> <tr> <td>Object(任何其它js對象)</td> <td><code>"object"</code></td> </tr> </tbody> </table>編程

例如:api

// string
typeof "" === "string";
typeof "abc" === "string" ;
typeof String("abc") === "string" ;
typeof (typeof 1) === "string" ;

// number
typeof 1 === "number" ;
typeof NaN === "number" ;
typeof Math.PI === "number" ;
typeof Infinity === "number" ;
typeof Number(1) === "number";

// boolean
typeof true === "boolean" ;
typeof false === "boolean" ;
typeof Boolean(false) === "boolean";

// undefined
typeof Undefined === "undefined" ;
typeof val === "undefined"; // 在js中經過var定義但未初始化的變量值爲undefined,任何未經過var定義且未初始化的變量的初值爲undefined

// function
typeof function(){} === "function" ; 
typeof String === "function" ;
typeof Object === "function" ;
typeof new Function() === "function" ;

// object
typeof {} === "object" ;
typeof [] === "object" ;
typeof new Date() === "object" ;
typeof new String("abc") === "object" ; // ---1
typeof new Number("abc") === "object" ; // ---2
typeof new Boolean("abc") === "object" ;// ---3
typeof null === "object"	// ---4

以上示例中,在判斷對象類型時1,2,3,4四種狀況比較特殊,其中1,2,3屬於一類,javascript中經過new操做符來建立對象,new後面跟的是構造器(constructor),javascript中沒有相似於java中的自動裝箱/拆箱(Auto-Boxing/Unboxing)機制來完成基本數據類型與其對應對象類型的自動轉換,語言的靈活性與語法的規範性不能兼得,因此在實際編程中只能靠約定儘可能避免這種會產生歧義的使用方式。數組

null值在邏輯上表示空對象指針,這也能夠理解typeof返回的返回值爲何是"object"了。因此非空對象類型的正確的判斷方式是瀏覽器

typeof val === "object" && val !== null

此外以上判斷對象類型的示例中忽略了javascript中的正則表達式。因爲瀏覽器之間的差別,對於正則表達式的判斷沒有一致性的實現,對於正則表達式而言,typeof可能會返回"object""function"函數

typeof /w/ === 'function' ;
typeof /w/ === 'object'

#####2.使用toString方法this

javascript語言環境中提供了一些標準的內建對象類型,其中Object類型是全部對象類型的基類,javascript中沒有純粹化的類型的概念,而是基於javascript中特有的繼承模式:原型鏈繼承,全部內建類型對象或自定義類型對象在建立後都會繼承Object.prototype中的屬性和方法,在Object的原型對象中的toString()方法會返回一個表明對象類型的字符串,該字符串的格式爲"[object type]",其中type則表明對象的類型。如:

var obj = new Object();
obj.toString(); // return [object Object]

所以只要自定義類型沒有重寫其原型對象中的toString()方法,或着派生自Object的對象沒有重寫toString()方法,那麼調用對象自己的toString()方法能夠正確得到其類型描述。如對於內建類型:

// date
new Date().toString(); // return [object Date]

// number
var val = 1 ;
new Number(1).toString();	// return [object Number]
val.toString(); // return [object Number]

// boolean
new Boolean(true).toString(); // return [object Boolean]
var val = true ;
val.toString(); // return [object Boolean]

// string
new String("").toString();// return [object String]
var val = 「」 ;
val.toString(); // return [object String]

// object
new Object().toString();// return [object Object]

// regexp
new Regexp().toString();// return [object Regexp]
var val = /w/ ;
val.toString();// return [object Regexp]

// array
new Array().toString();// return [object Array]
var val = [];
val.toString();// return [object Array]

// function
new Function().toString();// return [object Function]
var val = function(){};
val.toString();// return [object Function]

// error
new Error().toString();// return [object Error]

對於自定義類型:

function Person(name){
	this.name = name ;
}
new Person().toString();// return [object Object]

若是自定義類型覆蓋toString方法,如:

Person.prototype.toString = function(){
	return "Person Class";
}

那麼,以後

new Person().toString() // return Person Class

所以要在全部對象上都能使用原始的Object.ptototype.toString方法,須要結合Function.prototype.call方法,並將對象做爲this參數傳遞進call方法,如:

var _toString = Object.prototype.toString;

_toString.call(new Person());// return [object Object]

這樣相對於typeof來講,使用toString方法來判斷不但能區分變量是不是對象類型,甚至能夠判斷對象的是數組,日期,正則表達式,仍是函數。

Ecmascript5.1版本的規範中,toString上調用call方法,並將this參數設置爲nullundefined調用後,分別返回'null''undefined'

#####3.jQuery.type()的實現

jQuery中提供了一個用來判斷對象內建類型的方法jQuery.type,其內部實現則是結合typeoftoString方法實現的。實現流程其源碼以下:

  1. 定義保存類型的全稱與簡寫映射的對象

    // [[Class]] -> type pairs
     class2type = {},
  2. 定義保存Object.prototype.toString方法的變量,此處使用的是原型繼承來實現

    core_toString = class2type.toString,
  3. 創建實際的映射關係,[object type] -- > type

    // Populate the class2type map
     jQuery.each("Boolean Number String Function Array Date RegExp Object 		Error".split(" "), function(i, name) {
     	class2type[ "[object " + name + "]" ] = name.toLowerCase();
     });
  4. 實現jQuery.type方法,並擴展到jQuery中,如下是簡化版

    jQuery.extend({
     	type: function( obj ) {
     		if ( obj == null ) {
     			return String( obj );
     		}
     		return typeof obj === "object" || typeof obj === "function" ?
     		class2type[ core_toString.call(obj) ] || "object" :
     		typeof obj;
     	}
     });

jQuery.type方法調用返回的是字符串類型,全部返回值包括'object','null','undefined','date','number','function','array','string','regexp','boolean'

javascript中 null == undefined會返回true

具體實例,參見jQuery.type官網API

Reference:

相關文章
相關標籤/搜索