Javacript实现字典结构

字典是一种用[键,值]形式存储元素的数据结构。

也称作映射,ECMAScript6中,原生用Map实现了字典结构。

下面代码是尝试用JS的Object对象来模拟实现一个字典结构。

<script>
//set添加 get获取 has是否有 remove删除 values获取所有value size获取长度 clear清除所有
function Dict(){
    this.item = {};
}

//是否存在元素
Dict.prototype.has = function(key){
    return key in this.item;
}

//set添加元素
Dict.prototype.set = function(key,value){
    if(!this.has(key)){
        this.item[key] = value;
        return true;
    }
    return false;
}

//查找并返回元素
Dict.prototype.get = function(key){
    return this.has(key) ? this.item[key] : undefined;
}

//移除元素
Dict.prototype.remove = function(key){
    if(this.has(key)){
        delete this.item[key];
        return true;
    }
    return false;
}

//返回字典所包含元素的数量
Dict.prototype.size = function(key){
    var length = 0;
    for(var i in this.item){
        length++;
    }
    return length;
}

//清空字典所有元素
Dict.prototype.clear = function(){
    if(this.size() > 0){
        this.item = {};
        return true;
    }
    return false;
}

//把字典所有元素用数组的形式返回
Dict.prototype.values = function(){
    var values = []
    if(this.size() > 0){
        for(var i in this.item){
            values.push(i);
        }
        return values;
    }
}

var dict = new Dict();
dict.set('a',1);
dict.set('b',2);
dict.set('c',3);
console.log(dict.values()); //["a", "b", "c"]
dict.remove('b');
console.log(dict.size()); //2
dict.clear();
console.log(dict.size()); //0
console.log(dict.clear()); //false
</script>

原文链接:https://www.cnblogs.com/jaychan/p/5973297.html

posted @ 2019-10-02 01:12  meiyoufan  阅读(118)  评论(0)    收藏  举报