javascript 中定义 hashtable哈希表 类

     在哈希表类中,可以使用Array和Object来存储实质的 哈希表数据。Object具有更强的类型兼容新,使的Object可以以任意的数据类型的作为哈希表的下标key数据类型。

 

哈希表类定义 代码
//定义哈希表类
    function HashTable() {
        
this.hash = new Object();  // 创建Object对象 。存放key,及其对应的value的哈希表
        
//哈希表的添加方法
        this.add = function(key, value) {
            
if (typeof (key) != "undefined") {
                
if (this.contains(key) == false) {
                    
this.hash[key] = typeof (value) == "undefined" ? null : value;
                    
return true;
                } 
else {
                    
return false;
                }
            } 
else {
                
return false;
            }
        }
        
//哈希表的移除方法
        this.remove = function(key) {
            delete 
this.hash[key];
        }
        
//哈希表内部键的数量
        this.count = function() {
            var i 
= 0;
            
for (var k in this.hash) {
                i
++;
            }
            
return i;
        }
        
//通过键值获取哈希表的值
        this.items = function(key) {
            
return this.hash[key];
        }
        
//在哈希表中判断某个值是否存在 
        this.contains = function(key) {
            
return typeof (this.hash[key]) != "undefined";
        }
        
//清空哈希表内容的方法
        this.clear = function() {
            
for (var k in this.hash) {
                delete 
this.hash[k];
            }
        }
       //得到所有的值
        this.values = function() {
            var allValues = new Array()
            for (var k in this.hash) {
                allValues.push(this.hash[k]);
            }
            return allValues;
        }
        //得到所有的键
        this.keys = function() {
        var allKeys = new Array()
            for (var k in this.hash) {
                allKeys.push(k);
            }
            return allKeys;
        }
    }

 

       类中存储哈希表数据的this.hash类似于.net中list<T>,只是下标Key和其对应的值Value的数据类型可以任意。

 

posted @ 2010-02-26 10:34  爱图--UpdooGIS  阅读(425)  评论(0编辑  收藏  举报