萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 模擬 C# List 集合類完整實現

設計目標

在 JavaScript 中復刻 C# List<T> 的核心 API:動態數組、強類型語義、豐富操作方法、O(1) 索引訪問。

完整實現代碼 (ES5 兼容)

/**
 * List - 動態數組集合
 * @constructor
 */
function List() {
    this.list = []; // 底層數組
}

/**
 * 添加單個元素到末尾
 * @param {*} object
 */
List.prototype.add = function(object) {
    this.list[this.list.length] = object;
};

/**
 * 批量添加另一個 List 的所有元素
 * @param {List} listObject
 */
List.prototype.addAll = function(listObject) {
    this.list = this.list.concat(listObject.list);
};

/**
 * 獲取指定索引元素
 * @param {Number} index
 * @returns {*}
 */
List.prototype.get = function(index) {
    return this.list[index];
};

/**
 * 移除指定索引元素並返回
 * @param {Number} index
 * @returns {*}
 */
List.prototype.removeIndex = function(index) {
    var obj = this.list[index];
    this.list.splice(index, 1);
    return obj;
};

/**
 * 移除首個匹配的元素(引用相等)
 * @param {*} object
 * @returns {*} 被移除元素或 null
 */
List.prototype.remove = function(object) {
    for (var i = 0; i < this.list.length; i++) {
        if (this.list[i] === object) {
            return this.removeIndex(i);
        }
    }
    return null;
};

/**
 * 清空所有元素
 */
List.prototype.clear = function() {
    this.list.splice(0, this.list.length);
};

/**
 * 獲取元素數量
 * @returns {Number}
 */
List.prototype.size = function() {
    return this.list.length;
};

/**
 * 截取子列表 [start, end)
 * @param {Number} start
 * @param {Number} end
 * @returns {List}
 */
List.prototype.subList = function(start, end) {
    var sub = new List();
    sub.list = this.list.slice(start, end);
    return sub;
};

/**
 * 判斷是否為空
 * @returns {Boolean}
 */
List.prototype.isEmpty = function() {
    return this.list.length === 0;
};

測試用例

function test() {
    var list = new List();

    // 添加
    list.add("A");
    list.add("B");
    list.add("C");
    console.log("Size:", list.size()); // 3

    // 獲取
    console.log("Index 1:", list.get(1)); // "B"

    // 移除索引
    var removed = list.removeIndex(0);
    console.log("Removed:", removed); // "A"
    console.log("Size after removeIndex:", list.size()); // 2

    // 移除對象
    list.add("D");
    list.remove("B");
    console.log("After remove B:", list.get(0), list.get(1)); // "C", "D"

    // 子列表
    var sub = list.subList(0, 1);
    console.log("SubList size:", sub.size()); // 1

    // 清空
    list.clear();
    console.log("IsEmpty:", list.isEmpty()); // true
}

ES6 Class 現代化重寫

class List {
    constructor() {
        this._items = [];
    }

    get size() { return this._items.length; }
    get isEmpty() { return this._items.length === 0; }

    add(item) { this._items.push(item); return this; } // 支援鏈式
    addAll(otherList) { this._items.push(...otherList._items); return this; }

    get(index) { 
        if (index < 0 || index >= this._items.length) throw new RangeError("Index out of bounds");
        return this._items[index]; 
    }

    removeAt(index) {
        if (index < 0 || index >= this._items.length) return undefined;
        return this._items.splice(index, 1)[0];
    }

    remove(item) {
        const idx = this._items.indexOf(item);
        if (idx !== -1) return this.removeAt(idx);
        return undefined;
    }

    clear() { this._items.length = 0; }

    subList(start, end) {
        const sub = new List();
        sub._items = this._items.slice(start, end);
        return sub;
    }

    // 迭代器支援 for...of
    *[Symbol.iterator]() {
        for (const item of this._items) yield item;
    }

    // 轉數組
    toArray() { return [...this._items]; }
    toJSON() { return this.toArray(); }
}

對比:原生 Array vs List 封裝

特性ArrayList 封裝
語義 通用數組 明確集合語義、類型意圖
方法名 push/pop/splice... add/remove/get/size (C# 風格)
邊界檢查 無 (undefined) 可選拋出異常
事件/通知 無 可擴展添加 change 事件
性能 原生最優 極薄封裝,損耗可忽略

適用場景

  • 團隊來自 C#/.NET 背景,統一 API 風格降低認知負荷
  • 需要在集合操作上掛鉤邏輯(如變更通知、持久化、驗證)
  • 教學演示數據結構實現原理
  • 老舊環境無 Array.prototype 現代方法時的 Polyfill 基礎

結語

JavaScript 原生數組功能已極其強大,手寫 List 封裝主要為了語義統一和擴展點預留。現代項目推薦直接使用 Array + 類型註解,或引入 Immer(不可變)、MobX observable.array(響應式)等成熟方案。

copyright © 萬盛學電腦網 all rights reserved