首页 > web前端 > js教程 > 正文

在JavaScript中实现自己的Map对象

高洛峰
发布: 2016-11-25 14:12:42
原创
1473人浏览过

hashmap在程序设计中,具有无可替代的重要作用。它提供m.put(key,value); m.get(key);之类的数据存储及读取方式,非常方便。但在javascript(html4.0的版本) 中,并没有提供这样的一种对象。以下这段代码用于创建map对象,我已使用多年,效果良好,供需要的朋友参考。

 

 

 

一、Map源代码

立即学习Java免费学习笔记(深入)”;

 

 

    /**  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

 

 

 

 

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

 

 

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号