javascript 實現hashtable集合

看到一篇關於js 實現hashtable 的文章http://www.blogjava.net/fantasy/archive/2006/08/02/44742.html#61363

,挺不錯,考慮到現在很多網友都使用prototype開發,所以我用prototype的方式重新實現了這個hashtable 集合,並修正了一個小bug (hashtable中刪除對象前先判斷存在)。

//hashtable in javascript
var Collections = new Object();

Collections.Base = Class.create();
Collections.Base.prototype = {
 initialize:function()
 {
  this.count = 0 ;
  this.container = new Object();
 }
}
Collections.Hashtable = Class.create();
Collections.Hashtable.prototype = Object.extend(new Collections.Base(),
  { 
   add:function(key ,value)
   {
    if(!this.containsKey(key))
    {
     this.count++;
    }
    this.container[key] = value;
   },
   get:function(key)
   {
    if(this.containsKey(key))
    {
     return this.container[key];
    }
   else
    {
     return null;
    }
   },
   containsKey:function(key)
   {
    return (key in this.container);
   },
   containsValue:function(value)
   {
    for(var prop in this.container)
    {
     if(this.container[prop]==value)
     {
      return true;
     }
    }
    return false;
   },
   keys:function()
   {
    var keys = new Array();
    for(var prop in this.container)
    {
     keys.push(prop);
    }
    return keys;
   },
   values:function()
   {
    var values = new Array();
    for(var prop in this.container)
    {
     values.push(this.container[prop]);
    }
    return values;
   },
   remove:function()
   {
    if(this.containsKey(key))
    {
     delete this.container[key];
     this.count--;
    }
   }
    
  }

); 

 

調用方式可以如下

var ht = new Collections.Hashtable();

ht.add("guest1" ,"Jackson");

ht.add("guest2" ,"Tom");

取值

var name = ht.get("guest1");

其他方法應該比較直觀,不用多說了,呵呵!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章