在JavaScript中實現自己的Map對象

來源:互聯網
上載者:User

 

HashMap在程式設計中,具有無可替代的重要作用。它提供m.put(key,value); m.get(key);之類的資料存放區及讀取方式,非常方便。但在JavaScript(HTML4.0的版本) 中,並沒有提供這樣的一種對象。以下這段代碼用於建立Map對象,我已使用多年,效果良好,供需要的朋友參考。

 

 

 

一、Map原始碼

 

 

    /**  Map is a general map object for storing key value pairs

     *  @param m - default set of properties

     */

var Map =function(m) {

        var map;

        if (typeof m == 'undefined') map = new Array();

        else map = m;

       

        /**

         * Get a list of the keys to check

         */

        this.keys = function() {

            var _keys = new Array();

            for (var _i in map){

                _keys.push(_i);

            }

            return _keys;//

        };

        /**

         * Put stores the value in the table

         * @param key the index in the table where the value will be stored

         * @param value the value to be stored

         */

        this.put = function(key,value) {

            map[key] = value;

        };

        /**

         * Return the value stored in the table

         * @param key the index of the value to retrieve

         */

        this.get = function(key) {

            return map[key];

        };

        /**

         * Remove the value from the table

         * @param key the index of the value to be removed

         */

        this.remove =  function(key) {

            map[key]=null;

            delete map[key];

        };

        /**

         *  Clear the table

         */

        this.clear = function() {

            delete map;

            map = new Array();

        };

    }

 

 

 

二、建立Map對象

 

var m=new Map();

 

m.put("id","1000");

 

m.put("name","張三");

 

 

 

三、運用 www.2cto.com

 

<div id="testMap"'></div>

 

 <script type='text/javascript'>

 

      document.getElementById("testMap").innerHTML=m.get("name");

 

 </script>

 

摘自wj800的專欄

聯繫我們

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