一個用javascript寫的hashtable類

來源:互聯網
上載者:User

<script language="javascript" type="text/javascript">

function Hashtable()
{
    this._hash        = new Object();
    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";} //判斷key是否存在
    this.clear        = function(){for(var k in this._hash){delete this._hash[k];}}
 this.hasvalue        = function(value){
  for(var k in this._hash){
   if(this._hash[k]==value){
    return true;
   }
  }
  return false;
 }
 this.getallvalues        = function(){
  var tmp="";
  for(var k in this._hash){
   tmp += k+","+a._hash[k]+";";
  }
  return tmp;
 }
 this.getjosnvalues        = function(){
  var tmp="{";
  for(var k in this._hash){
   tmp += k+":"+a._hash[k]+",";
  }
  tmp+="}";
  return tmp;
 }
 this.getjosnitems        = function(){
  var tmp="[";
  for(var k in this._hash){
   tmp += "{"+k+":"+a._hash[k]+"},";
  }
  tmp=tmp.substring(0,tmp.length-1)+"]";
  return tmp;
 }
}

var a = new Hashtable();

a.add("aa");
a.add("bb",2342);
a.add("bb",2344);

alert(a.hasvalue(2342));

a.add("cc",2342);

for(var k in a._hash){
 alert(k+":"+a._hash[k]);
}

alert("移除");
a.remove("aa");

for(var k in a._hash){
 alert(k+":"+a._hash[k]);
}

alert("a.getallvalues():"+a.getallvalues());
alert("this.getjosnitems():"+this.getjosnitems());


/*
alert("計算總數");
alert(a.count());
alert("顯示bb是否是數字");
alert(a.contains("bb"));
alert("顯示aa是否是數字");
alert(a.contains("aa"));
alert("顯示bb內容");
alert(a.items("bb"));
alert("顯示aa內容");
alert(a.items("aa"));
*/
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.