Javascript 类数组对象

第三方教程:

https://segmentfault.com/a/1190000000415572
http://www.jb51.net/article/59169.htm

 

何为类数组?

么是类数组对象:它首先是一个对象,其次与数组相似,它拥有 length 属性,但却不能使用数组的方法(Array.prototype)。

只要一个对象Object,拥有 length 属性,那它就是一个类数组对象。譬如:

- document.getElementsByTagName()语句返回的就是一个类数组对象。

- 在function中,function代码内的arguments变量也是一个类数组对象。

var a = function () {
    console.log(arguments) // { '0': 1, '1': 2, '2': 3, '3': 4 }
    console.log(arguments.length) // 4
}

a(1, 2, 3, 4)

 

自定义类数组对象,但是对象的 key 必须是 Number 类型。

var a = {
    '0':'a',
    '1':'b',
    '2':'c',
    length:3
};

 

像数组一样使用类数组

之所以成为“类数组”,就是因为和“数组”类似。不能直接使用数组方法,但你可以像使用数组那样,使用类数组。

var likeArrayObject = {
    '0':'a',
    '1':'b',
    '2':'c',
    length:3
};

// 转为数组
Array.prototype.slice.call( likeArrayObject ); // [ 'a', 'b', 'c' ]

// 取出第一位
Array.prototype.shift.call( likeArrayObject ) // a

// 数组转为字符串累加
Array.prototype.join.call( likeArrayObject, ' + ' ); // a + b + c

// 使用数组的map遍历方法,逐个转化为大写并且返回到新数组中
Array.prototype.map.call( likeArrayObject, function(x) { return x.toUpperCase(); }); // [ 'A', 'B', 'C' ]


类数组判断
《javascript权威指南》上给出了代码用来判断一个对象是否属于“类数组”。如下:

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
}
posted @ 2017-03-06 17:39  贝尔塔猫  阅读(297)  评论(0编辑  收藏  举报