js数据结构与算法——字典与散列表

   <script>
        
        //创建字典
        function Dictionary(){
            var items = {};

            this.set = function(key,value){
                //向字典添加一个新的项
                items[key] = value;
            }

            this.remove = function(key){
                //从字典移除一个值
                if(this.has(key)){
                    delete items[key];
                    return true;
                }
                return false;
            }

            this.has = function(key){
                //判断值是否在字典中,返回布尔值
                return key in items;
            }
            
            this.get = function(key){
                //通过键值查找特定的数值并返回
                return this.has(key) ? items[key] : undefined;
            }

            this.clear = function(){
                //清空字典
                items = {};
            }

            this.size = function(){
                //返回字典的元素数量
                return Object.keys(items).length;
            }
            
            this.keys = function(){
                //返回字典的键值名
                return Object.keys(items);
            }

            this.values = function(){
                //返回一个包含字典中所有值的数组
                var values = [];
                for(var key in items){
                    if(this.has(key)){
                        values.push(items[key])
                    }
                }
                return values;
            }

            this.getItems = function(){
                //返回items
                return items;
            }

        }

        var dictionary = new Dictionary();
        dictionary.set('Gandalf', '[email protected]');
        dictionary.set('John', '[email protected]');
        dictionary.set('Tyrion', '[email protected]'); 
        console.log(dictionary.getItems());
    </script>

猜你喜欢

转载自www.cnblogs.com/huangmin1992/p/10415337.html