数据结构——字典(JavaScript)

来源:互联网 发布:数据库面试宝典 编辑:程序博客网 时间:2024/06/17 12:41

创建字典

function Dictionary(){//首先申明一个类    var items = {};    this.set = function(Key,value){//向字典中添加新元素        items[Key] = value;    }    this.remove = function(Key){//通过使用键值对来从字典中移除键值对应的数据值        if(Key in items){            delete items[Key];            return true;        }else{            return false;        }    }    this.has = function(Key){//如果某个键值存在于这个字典中,就返回true,否则返回false        return Key in items;    }    this.get = function(Key){//通过键值查找指定的数值并返回        return this.has(Key) ? items[Key] : undefined;    }    this.clear = function(){//删除字典中所有的元素        items = {};        return true;    }    this.size = function(){//返回字典所包含元素的数量        return this.Keys().length;    }    this.Keys = function(){        var keys = [];        for(var k in items){            if(this.has(k)){                keys.push(k);            }        }        return keys;    }    this.values = function(){//将字典所包含的所有数值以数组形式返回        var values = [];        for(var k in items){            if(this.has(k)){                values.push(items[k]);            }        }        return values;    }    this.getItems = function(){        return items;    }}

使用Dictionary类

var dictionary = new Dictionary();dictionary.set('Tom','123@qq.com');dictionary.set('Bob','456@163.com');dictionary.set('John','789@126.com');console.log(dictionary.has('Tom'));console.log(dictionary.size());console.log(dictionary.Keys());console.log(dictionary.values());console.log(dictionary.get('Bob'));console.log(dictionary.remove('John'));console.log(dictionary.size());console.log(dictionary.Keys());console.log(dictionary.values());console.log(dictionary.getItems());

控制台输出

这里写图片描述