在JS中封装ListMapSet等集合

在前端,我们通常需要用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];
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理