在JS中封裝List、Map、Set等集合

在前端,我們通常需要用JS處理一些從服務器返回的數據,例如簡單的數據清洗、對數據格式做細微的調整等等,這些需求在java中藉助集合通常很容易完成,但JS原生不提供類似java中的集合,這時,我們可以利用JS中的原生數組和Object對象來封裝List、Map、Set這些集合,下面依次說明如何封裝這些集合。

List

List結構本身可以看作一個線性數組,因此可以利用數組來封裝,首先,定義List中的數組和各類方法。

function List(){
    this.values = new Array();
    this.add = function(a){
        this.values.push(a);
    }
    this.get = function(index){
        if(index >= this.values.length){
            console.error("index is out range of the max index");
        }else{
            return values[index];
        }
    }
    ......
}

Map

Map用來存儲key-Value,與JS中的Object對象很相似,因此,可以通過封裝Object對象,定義一系列方法來構造Map。

function Map(){
    this.objs = {};
    this.put = function(key ,value){
        this.objs[key] = value;
    }
    this.get = function(key){
        if(key in this.objs){
            return this.objs[key];
        }else{
            console.debug("this key is not in the Map");
        }
    }
    this.keys = function(){
        var a = new Array();
        for(var b in this.objs){
            a.push(b);
        }
        return a;
    }
    this.delete = function(key){
        delete this.objs[key];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章