Javascript 中 HashMap 實現

來源:互聯網
上載者:User

    諸如HashMap、Stack、Queue都可以通過操作JS數組進行實現。下面我們首先參照Javascript官方使用手冊對JS Array對象中的一些常用函數進行解釋一下,以便進行下面的資料結構的實現(JS Array對象類似於堆棧的元素進出棧順序):
  Push :  添加一個元素
  Reverse:將數組元素進行逆序
  Shift:移除數組中第一個元素(下標為0)  

  Pop:彈出最後一個元素(下標為array.length-1)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head>  <title> New Document </title>  <script type="text/javascript">     function HashMap(){ this.source = new Array(); this.length = 0;   };   /*將函數列表(實為JSON資料)映射到HashMap的prototype屬性中*/  function Apply(o, c){      if(o && c && typeof c == 'object'){for(var p in c){o[p] = c[p];}}return o;  };  Apply(HashMap.prototype,{   /*擷取元素的個數*/size : function(){ return  this.length },/*查看是否存在該key值*/containsKey :function (key) {          if(this.source[key])  return true;else           return false;      },     /*查看是否存在該value值*/containsValue :function (value) {          for (var key in this.source) {              if (this.source[key] == value) {                  return true;              }          }          return false;      }, /*存入資料   傳回值如果為false表示該key值已經存過資料,我們會替換前一條資料*/put : function(key,value)    {   var tag = this.containsKey(key);   this.length += ((tag)? 0: 1);   this.source[key] = value;          return !tag;     },    /*根據key讀取資料*/    get :  function(key)       { return this.source[key];       },     /* 根據key值刪除HashMap中元素,返回刪除元素的value */       remove : function(key)        {        var value = this.source[key];         if( this.containsKey(key) && ( delete this.source[key] ) )            {                this.length --;            }            return value;     }, /*清除所有資料*/ clear : function() {   delete this.source;   this.source = new Array();   this.length = 0;   return 0; },      obj2str :function(o) {          var r = [];          if (typeof o == "string")              return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";          if (typeof o == "object") {              for (var i in o)                  r.push("\"" + i + "\":" + this.obj2str(o[i]));              if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {                  r.push("toString:" + o.toString.toString());              }              r = "{" + r.join() + "}";              return r;          }          return o.toString();       }, /*將資料以JSON字串形式輸出*/ toString : function() {     return this.obj2str(this.source); }    });  var hsp = new HashMap(); document.writeln(hsp.put('a',"apple"));   //true document.writeln(hsp.put('b',"boy"));     //true document.writeln(hsp.put('c',"cat"));    //true document.writeln(hsp.put('a',"replaceApple"));  //false document.writeln(hsp.get("a"));   //"replaceApple" document.writeln(hsp.size());     //3 document.writeln(hsp.containsValue('cat'));  //true document.writeln(hsp.containsKey('a'));  //true document.writeln(hsp.remove('a'));    //"replaceApple" document.writeln(hsp.toString());   //"{"b":"boy","c":"cat"}" document.writeln(hsp.clear());    //2 document.writeln(hsp.toString());   "{}"   </script> </head> <body>   </body></html>

註:Stack和Queue的實現可以參看: http://blog.csdn.net/wdxgdiy/article/details/8877565   寫的不錯

附件下載 :  http://pan.baidu.com/share/link?shareid=3844618167&uk=1763003608

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.