從javascript判斷一個對象是否爲數組中學習js語法

1,真正的數組的判斷方法

javascript中最簡單的聲明數組方法爲:

var a = [];

判斷是否爲數組的最直接的方法爲:

a instanceof Array //true
a .constructor == Array //true

這裏涉及到一個instanceof語法,instanceof是一個雲算符,與"+-*/"一樣,它的語法如下:

result = obj intanceof class

是用來判斷一個對象是否是某個class的一個實例,運算結果返回true或者false。javascript中class的定義又是通過構造函數進行初始化的,所以instanceof語法的右操作符class一定是Function的實例,即class instanceof Function一定爲true,而且如果使用instanceof時右操作符不是Function,就會拋出TypeError異常。所有對象都是Object的實例,所以任何對象instanceof Object都返回true。雖然我們說對象都是通過構造函數進行初始化的,但是instanceof卻不是通過檢查對象是否由該函數構造的,而是通過是否由構造函數的prototype繼承來的,下面這個例子可以說明這個問題:

function Range(low, high) {
this.low = low;
this.high = high;
}
Range.prototype.constructor == Range; //true
Range.prototype = {
include: function(x){ return (x >= this.low && x <= this.high); },
exclude: function(x){ return (x < this.low && x > this.high); }
}
var r = new Range(0, 100);
r instanceof Range; //false
r instanceof Object; //true
Range.prototype.constructor == Objecct; //true

這裏雖然r是通過new Range構造的,但是r卻並不是Range的實例,這就是問題所在,Range.prototype賦值語句覆蓋了默認的構造函數,沒對prototype賦值之前Range.prototype.constructor爲Range,賦值之後變成了Object,這也好理解,因爲

Range.prototype = {
include: function(x){ return (x >= this.low && x <= this.high); },
exclude: function(x){ return (x < this.low && x > this.high); }
}

其實等價於:

Range.prototype = new Object({
include: function(x){ return (x >= this.low && x <= this.high); },
exclude: function(x){ return (x < this.low && x > this.high); }
});

所以Range.prototype.constructor == Object,那麼通過new Range創建出來的實例當然就是Object的一個實例了。

看官方解釋更直接些:

The instanceof operator does not actually check whether r was initialized by the Range constructor. It checks whether it inherits from Range.prototype.

javascript中還有一個函數typeof具有與instanceof類似的功能,但是它返回的是具體的基本數據類型:number,string,function,object,undefined,boolean,只有這六種,不在這六種範圍內的都返回object,也就是說typeof([])返回的是object,而不是array。

另一個涉及到的語法是constructor,constructor返回對象的構造函數:

var a  = [];
a.constructor; //Array

構造函數是一個對象的初始化函數,採用new調用,如果對象是一個Array,那麼其constructor應該就是Array,自己寫的類就不一定了,因爲可能會吧prototype中的constructor更改掉。


2,僞數組的判斷方法

javascript中有一種僞數組,它可以使用類似於Array的遍歷方法進行遍歷,有length屬性獲取元素的長度,可以使用[]下標來獲取指定的元素,這種對象我們稱之爲僞數組,JQuery中的對象就是典型的僞數組,如下圖:


所以判斷是否是僞數組的關鍵就是判斷是否有length屬性,是否存在基本的數組操作函數splice,下面就是判斷方法:

var is_array = function(value) {
return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

這裏propertyIsEnumerable就是用來判斷length屬性是否可列舉,其實原生的String對象也是有類似Array的效果,但是我們不能把它當作Array對象,所以這裏需要判斷typeof value == "object",因爲typeof一個String對象,返回的是string。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章