建立健壯的isArray()函數(JavaScript中判斷物件類型的種種方法)

來源:互聯網
上載者:User

我們知道,JavaScript中檢測物件類型的運算子有:typeof、instanceof,還有對象的constructor屬性:

1) typeof 運算子
typeof 是一元運算子,返回結果是一個說明運算數類型的字串。如:"number","string","boolean","object","function","undefined"(可用於判斷變數是否存在)。
但 typeof 的能力有限,其對於Date、RegExp類型返回的都是"object"。如:

typeof {}; // "object"
typeof []; // "object"
typeof new Date(); // "object"

所以它只在區別對象和原始類型的時候才有用。要區一種物件類型和另一種物件類型,必須使用其他的方法。如:instanceof 運算子或對象的 constructor 屬。

2)instanceof 運算子。
instanceof 運算子要求其左邊的運算數是一個對象,右邊的運算數是對象類的名字或建構函式。如果 object 是 class 或建構函式的執行個體,則 instanceof 運算子返回 true。如果 object 不是指定類或函數的執行個體,或者 object 為 null,則返回 false。如:

[] instanceof Array; // true
[] instanceof Object; // true
[] instanceof RegExp; // false
new Date instanceof Date; // true

所以,可以用instanceof運算子來判斷對象是否為數群組類型:

function isArray(arr)
{
return arr instanceof Array;
}

3)constructor 屬性。
JavaScript中,每個對象都有一個constructor屬性,它引用了初始化該對象的建構函式,常用於判斷未知對象的類型。如給定一個求知的值通過typeof運算子來判斷它是原始的值還是對象。如果是對象,就可以使用constructor屬性來判斷其類型。所以判斷數組的函數也可以這樣寫:

function isArray(arr)
{
return typeof arr == "object" && arr.constructor == Array;
}

很多情況下,我們可以使用instanceof運算子或對象的constructor屬性來檢測對象是否為數組。例如很多JavaScript架構就是使用這兩種方法來判斷對象是否為數群組類型。
但是檢測在跨架構(cross-frame)頁面中的數組時,會失敗。原因就是在不同架構(iframe)中建立的數組不會相互共用其prototype屬性。例如:

<script>
window.onload=function(){
var iframe_arr=new window.frames[0].Array;
alert(iframe_arr instanceof Array); // false
alert(iframe_arr.constructor == Array); // false
}
</script>

<body>
<iframe></iframe>
</body>

在Ajaxian上看到了一種精確的檢測方法,跨原型鏈調用toString()方法:Object.prototype.toString()。可以解決上面的跨架構問題。

當Object.prototype.toString(o)執行後,會執行以下步驟:
1)擷取對象o的class屬性。
2)連接字串:"[object "+結果(1)+"]"
3)返回 結果(2)

例如:

Object.prototype.toString.call([]); // 返回 "[object Array]"
Object.prototype.toString.call(/reg/ig); // 返回 "[object RegExp]"

這樣,我們就可以寫一個健壯的判斷對象是否為數組的函數:

function isArray(arr)
{
return Object.prototype.toString.call(arr) === "[object Array]";
}

此種方法得到國外多個javaScript大師的認可,在即將發布的jQuery 1.3中將使用這種方法來檢測數組。

prototype.js的一個維護者寫了下面這個函數,用於擷取對象的類型名
/**
* Returns internal [[Class]] property of an object
*
* Ecma-262, 15.2.4.2
* Object.prototype.toString( )
*
* When the toString method is called, the following steps are taken:
* 1. Get the [[Class]] property of this object.
* 2. Compute a string value by concatenating the three strings "[object ", Result (1), and "]".
* 3. Return Result (2).
*
* __getClass(5); // => "Number"
* __getClass({}); // => "Object"
* __getClass(/foo/); // => "RegExp"
* __getClass(''); // => "String"
* __getClass(true); // => "Boolean"
* __getClass([]); // => "Array"
* __getClass(undefined); // => "Window"
* __getClass(Element); // => "Constructor"
*
*/
function __getClass(object)
{
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
};

擴充一下,用於檢測各種物件類型:
var is =
{
types : ["Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument"]
}
;
for(var i = 0, c; c = is.types[i ++ ]; )
{
is[c] = (function(type)
{
return function(obj)
{
return Object.prototype.toString.call(obj) == "[object " + type + "]";
}
}
)(c);
}
alert(is.Array([])); // true
alert(is.Date(new Date)); // true
alert(is.RegExp(/reg/ig)); // true

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.