javascript 類數組對象

原文:http://www.javashuo.com/article/p-pojgutlf-x.htmljavascript

定義:java

  • 擁有length屬性,其餘屬性(索引)爲非負整數(對象中的全部會被當作字符串來處理,這裏你能夠當作是個非負整數串來理解)
  • 不具備數組所具備的方法

類數組示例:

var a = {'1':'gg','2':'love','4':'meimei',length:5};
Array.prototype.join.call(a,'+');//'+gg+love++meimei'

非類數組示例:

var c = {'1':2};

沒有length屬性,因此就不是類數組。node

javascript中常見的類數組有arguments對象和DOM方法的返回結果。
好比 document.getElementsByTagName()segmentfault

類數組判斷

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

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

類數組表現

之因此成爲「類數組」,就是由於和「數組」相似。不能直接使用數組方法,但你能夠像使用數組那樣,使用類數組。ide

var a = {'0':'a', '1':'b', '2':'c', length:3};  // An array-like object
Array.prototype.join.call(a, '+'');  // => 'a+b+c'
Array.prototype.slice.call(a, 0);   // => ['a','b','c']: true array copy
Array.prototype.map.call(a, function(x) { 
    return x.toUpperCase();
});                                 // => ['A','B','C']:

類數組對象轉化爲數組

有時候處理類數組對象的最好方法是將其轉化爲數組。spa

Array.prototype.slice.call(arguments)

而後就能夠直接使用數組方法啦。prototype

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

對於IE9之前的版本(DOM實現基於COM),咱們能夠使用makeArray來實現。code

// 僞數組轉化成數組
var makeArray = function(obj) {
    if (!obj || obj.length === 0) {
        return [];
    }
    // 非僞類對象,直接返回最好
    if (!obj.length) {
        return obj;
    }
    // 針對IE8之前 DOM的COM實現
    try {
        return [].slice.call(obj);
    } catch (e) {
        var i = 0,
            j = obj.length,
            res = [];
        for (; i < j; i++) {
            res.push(obj[i]);
        }
        return res;
    }

};
相關文章
相關標籤/搜索