javascript類數組

1、類數組定義:

而對於一個普通的對象來講,若是它的全部property名均爲正整數,同時也有相應的length屬性,那麼雖然該對象並非由Array構造函數所建立的,它依然呈現出數組的行爲,在這種狀況下,這些對象被稱爲「類數組對象」。總而言之,具備如下兩點的對象:javascript

  • 擁有length屬性,其它屬性(索引)爲非負整數
  • 不具備數組所具備的方法

 

類數組示例:

如下是一個簡單的類數組對象:
var o = {0:42, 1:52, 2:63, length:3}
 console.log(o);

類數組的其餘常見狀況:如下是一個簡單的類數組對象:
//1.在ECMAScript 5標準中,字符串string就是一個只讀的類數組對象:
//2.在瀏覽器環境中,DOM方法的返回結果。如:document.getElementsByTagName()語句返回的就是一個類數組對象。
//3.在function調用中,function代碼內的arguments變量(保存傳入的參數)也是一個類數組對象。
 

2、類數組表現

與普通對象不一樣的是,類數組對象擁有一個特性:能夠在類數組對象上應用數組的操做方法。java

好比,在ECMAScript 5標準中,能夠用如下方法來將上面的對象o合併成字符串:node

console.log(Array.prototype.join.call(o));//"42,52,63"

也能夠在類數組對象上使用slice()方法獲取子數組:es6

console.log(Array.prototype.slice.call(o, 1, 2));//[52]

 

3、類數組判斷:

《javascript權威指南》上給出了代碼用來判斷一個對象是否屬於「類數組」。以下:segmentfault

 1 // Determine if o is an array-like object.
 2 // Strings and functions have numeric length properties, but are 
 3 // excluded by the typeof test. In client-side JavaScript, DOM text
 4 // nodes have a numeric length property, and may need to be excluded 
 5 // with an additional o.nodeType != 3 test.
 6 function isArrayLike(o) {
 7     if (o &&                                // o is not null, undefined, etc.
 8         typeof o === 'object' &&            // o is an object
 9         isFinite(o.length) &&               // o.length is a finite number
10         o.length >= 0 &&                    // o.length is non-negative
11         o.length===Math.floor(o.length) &&  // o.length is an integer
12         o.length < 4294967296)              // o.length < 2^32
13         return true;                        // Then o is array-like
14     else
15         return false;                       // Otherwise it is not
16 }

 

4、類數組對象轉化爲數組的幾種方式:

方式一:利用數據原型方法Array.prototype.slice.call(arguments)

var a = {'0':1,'1':2,'2':3,length:3};
var arr = Array.prototype.slice.call(a);//arr=[1,2,3]

方式二:es5以前利用循環遍歷

 1 // 僞數組轉化成數組
 2 var makeArray = function(obj) {
 3     if (!obj || obj.length === 0) {
 4         return [];
 5     }
 6     // 非僞類對象,直接返回最好
 7     if (!obj.length) {
 8         return obj;
 9     }
10     // 針對IE8之前 DOM的COM實現
11     try {
12         return [].slice.call(obj);
13     } catch (e) {
14         var i = 0,
15             j = obj.length,
16             res = [];
17         for (; i < j; i++) {
18             res.push(obj[i]);
19         }
20         return res;
21     }
22 
23 };

方式三:es6新增擴展運算符

在瀏覽器環境中,document.getElementsByTagName()語句返回的就是一個類數組對象。
var a = document.getElementsByTagName('p');
var arr = ...a;
在ECMAScript 5標準中,字符串string就是一個只讀的類數組對象:
var arr = ...「abc」;//['a', 'b', 'c'];
注意:es8新增擴展運算符對對象的支持。

 

javascript類數組:http://www.javashuo.com/article/p-pojgutlf-x.html數組

相關文章
相關標籤/搜索