JS判斷對象是否是數組「Array」

在開發中,咱們常常須要判斷某個對象是否爲數組類型,在Js中檢測對象類型的常見方法都有哪些呢?


typeof 操做符


對於Function, String, Number ,Undefined 等幾種類型的對象來講,他徹底能夠勝任,可是爲Array時


var arr=new Array("1","2","3","4","5");
alert(typeof(arr));
你會收到一個object 的答案,有點讓人失望。


instanceof 操做符


JavaScript中instanceof運算符會返回一個 Boolean 值,指出對象是不是特定類的一個實例。 使用方法:result = object instanceof class,仍是剛剛的數組,再來一次,嗯,成功的返回 true。


var arrayStr=new Array("1","2","3","4","5");
alert(arrayStr instanceof Array);
小總結:看樣子咱們今天討論的問題已經獲得瞭解答,但事實上在多個frame中穿梭就會產生大問題了。


var iframe = document.createElement('iframe');   
document.body.appendChild(iframe);   
xArray = window.frames[window.frames.length-1].Array;      
var arr = new xArray("1","2","3","4","5");//這個寫法IE大哥下是不支持的,FF下才有
alert(arr instanceof Array); // false
alert(arr.constructor === Array); // false
返回結果爲兩個False,讓人大失所望。


ECMA-262 寫道


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]],而後把類型檢測轉化爲字符串比較,以達到咱們的目的。仍是先來看看在ECMA標準中Array的描述吧。


ECMA-262 寫道


new Array([ item0[, item1 [,…]]])
The [[Class]] property of the newly constructed object is set to 「Array」.


因而利用這點,第三種方法登場了。


function isArray(obj) {  
  return Object.prototype.toString.call(obj) === '[object Array]';   
}
call改變toString的this引用爲待檢測的對象,返回此對象的字符串表示,而後對比此字符串是不是'[object Array]',以判斷其是不是Array的實例。也許你要問了,爲何不直接o.toString()?嗯,雖然Array繼承自Object,也會有toString方法,可是這個方法有可能會被改寫而達不到咱們的要求,而Object.prototype則是老虎的屁股,不多有人敢去碰它的,因此能必定程度保證其「純潔性」:) 數組

相關文章
相關標籤/搜索