Chinaunix首页 | 论坛 | 博客
  • 博客访问: 79836
  • 博文数量: 15
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 210
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-19 16:54
文章分类

全部博文(15)

文章存档

2009年(2)

2008年(13)

我的朋友

分类: 系统运维

2008-04-24 19:15:59

刚刚从网上看到一篇关于javascript实现的hashtable方法,觉得不错,现转载如下,供以后学习使用,感谢tlping:

//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");

其他方法应该比较直观,不用多说了,呵呵!

 
阅读(782) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~