JS中判斷對象是否是數組的方法

今天有同事忽然問到如何判斷一個對象是否是數組,當時只想到啦instanceof操做符,後來又蒐集了一些文章,總結出如下方法。數組

1、typeof 操做符

在js中使用typeof操做符來判斷function string number boolean undefined等是沒有問題的。可是若是要檢測Array就沒有做用了,由於typeof判斷arraynull的結果都是object瀏覽器

alert(typeof null); // "object"
alert(typeof function () {
return 1;
}); // "function"
alert(typeof 'abcd'); // "string"
alert(typeof true); //boolean
alert(typeof 1); // "number"
alert(typeof a); // "undefined"
alert(typeof undefined); // "undefined"
alert(typeof []); // "object"
複製代碼

2、instanceof 操做符

var arr = [];
console.log(arr instanceof Array);
複製代碼

arr instanceof Array的含義是:判斷Arrayprorotype屬性是否是在arr的原型鏈上,是返回true,否返回false;bash

3、對象的constructor屬性

除了instanceof,每一個對象還有constructor的屬性,利用它彷佛也能進行Array的判斷app

var arr = [];
console.log(arr.constructor === Array);
複製代碼

4、instanceof 和 constructor 的缺陷

經過使用 instanceof 和 constructor 來判斷對象是否是數組,在大多數狀況下是能夠的,但實際上也仍是有缺陷的,當頁面上有多個frame,須要在多個iframe中來回切換時,這種方法的缺陷就表現出來啦。ui

因爲每一個iframe都有一套本身的執行環境,跨frame實例化的對象彼此是不共享原型鏈的,所以致使instanceofconstructor失效。this

var iframe = document.createElement('iframe'); //建立iframe
document.body.appendChild(iframe); //添加到body中
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // 聲明數組[1,2,3]
alert(arr instanceof Array); // false
alert(arr.constructor === Array); // false 
複製代碼

5、Object.prototype.toString

Object.prototype.toString的行爲:首先,取得對象的一個內部屬性[[Class]],而後依據這個屬性,返回一個相似於"[object Array]"的字符串做爲結果(看過ECMA標準的應該都知道,[[]]用來表示語言內部用到的、外部不可直接訪問的屬性,稱爲「內部屬性」)。利用這 個方法,再配合call,咱們能夠取得任何對象的內部屬性[[Class]],而後把類型檢測轉化爲字符串比較,以達到咱們的目的。spa

function isArrayFn (o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
var arr = [1,2,3,1];
alert(isArrayFn(arr));// true 
複製代碼

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

JavaScript 標準文檔中定義: [[Class]] 的值只多是下面字符串中的一個: Arguments, Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, String. 這種方法在識別內置對象時每每十分有用,但對於自定義對象請不要使用這種方法。code

6、Array.isArray()

ECMAScript5中引入了Array.isArray()方法,用於專門判斷一個對象是否是數組,是返回true,不是返回false;目前全部主流瀏覽器和IE9+都對其進行了支持,IE8及如下瀏覽器不支持該方法。對象

7、一種最佳的判斷方法

綜合以上方法的優缺點,能夠有一個最佳的判斷數組的寫法:

var arr = [1,2,3,1];
var arr2 = [{ abac : 1, abc : 2 }];
function isArrayFn(value){
    if (typeof Array.isArray === "function") {
        return Array.isArray(value);
    }else{
        return Object.prototype.toString.call(value) === "[object Array]";
    }
}
console.log(isArrayFn(arr));// true
console.log(isArrayFn(arr2));// true
複製代碼
相關文章
相關標籤/搜索