js類比C#中List的簡單一實例

來源:互聯網
上載者:User

複製代碼 代碼如下:
/*
 * List 大小可變數組
 * version: 1.0
 */
function List() {
    this.list = new Array();
};

/**
 * 將指定的元素添加到此列表的尾部。
 * @param object 指定的元素
 */
List.prototype.add = function(object) {
    this.list[this.list.length] = object;
};

/**
 * 將List添加到此列表的尾部。
 * @param listObject 一個列表
 */
List.prototype.addAll = function(listObject) {
    this.list = this.list.concat(listObject.list);
};

/**
 *  返回此列表中指定位置上的元素。
 * @param index 指定位置
 * @return 此位置的元素
 */
List.prototype.get = function(index) {
    return this.list[index];
};

/**
 * 移除此列表中指定位置上的元素。
 * @param index 指定位置
 * @return 此位置的元素
 */
List.prototype.removeIndex = function(index) {
    var object = this.list[index];
    this.list.splice(index, 1);   
    return object;
};

/**
 * 移除此列表中指定元素。
 * @param object 指定元素
 * @return 此位置的元素
 */
List.prototype.remove = function(object) {
    var i = 0;
    for(; i < this.list.length; i++) {       
        if( this.list[i] === object) {
            break;
        }       
    }
    if(i >= this.list.length) {
        return null;
    } else {
        return this.removeIndex(i);
    }
};

/**
 * 移除此列表中的所有元素。
 */
List.prototype.clear = function() {
    this.list.splice(0, this.list.length);
};

/**
 * 返回此列表中的元素數。
 * @return 元素數量
 */
List.prototype.size = function() {
    return this.list.length;
};

/**
 * 返回列表中指定的 start(包括)和 end(不包括)之間列表。
 * @param start 開始位置
 * @param end   結束位置
 * @return  新的列表
 */
List.prototype.subList = function(start, end) {   
    var list = new List();
    list.list = this.list.slice(start, end);
    return list;
};

/**
 *  如果列表不包含元素,則返回 true。
 * @return true or false
 */
List.prototype.isEmpty = function() {
    return this.list.length == 0;
};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.