日期:2014-05-16  浏览次数:20318 次

自己封装js的ArrayList类

众所周之,js是没有ArrayList类的,但是js自带了Array类(虽然在js中已经是动态数组了),不过Array类使用起来还是挺别扭的,尤其是一些方法名称,更是让人摸不着头脑,于是就有了自己封装一个ArrayList类的想法。

?

?

(function(win) {
    var ArrayList = function() {
        this.datas = [];
    };

    var proto = ArrayList.prototype;

    proto.size = function() {
        return this.datas.length;
    };

    proto.isEmpty = function() {
        return this.size() === 0;
    };

    proto.contains = function(value) {
        return this.datas.indexOf(value) !== -1;
    };

    proto.indexOf = function(value) {
        for ( var index in this.datas) {
            if (this.datas[index] === value) {
                return index;
            }
        }

        return -1;
    };

    proto.lastIndexOf = function(value) {
        for ( var index = this.size(); index >= 0; index--) {
            if (this.datas[index] === value) {
                return index;
            }
        }
    };

    proto.toArray = function() {
        return this.datas;
    };

    proto.outOfBound = function(index) {
        return index < 0 || index > (this.size() - 1);
    };

    proto.get = function(index) {
        if (this.outOfBound(index)) {
            return null;
        }

        return this.datas[index];
    };

    proto.set = function