zoukankan      html  css  js  c++  java
  • 【javascript】js实现容器Map

    js实现容器Map

    var可以定义一个局部变量,当然如果var定义在最外层的话,就是全局的局部变量,也就算是全局变量了。

    this关键字定义的变量准确的说应该算是成员变量。即定义的是调用对象的成员变量。

    另外在“类(构造函数)”中,我们通常也会用var定义私有属性,而this定义公共属性。

    在该博客中,实现的是容器Map的增加,删除,查询,打印功能。源码如下:

    <script>
        function Map() {
            var map = function(key, value) {//键值对
                this.key = key;
                this.value = value;
            }
            var put = function(key, value) {//添加键值对
    
                this.arr[this.arr.length] = new map(key, value);
            }
            var remove = function(key) {//删除key="key"的键值对,返回value值
                for (var i = 0; i < this.arr.length; i++) {
                    var temp = this.arr.pop();
                    if (this.arr[i].key === key) {
    
                        return this.arr[i].value;
                    }
                    this.arr.push(temp);
                }
                return null;
            }
            var getKey = function(value) {//返回key对应的value值
                for (var i = 0; i < this.arr.length; i++) {
                    if (this.arr[i].value === value)
                        return this.arr[i].key;
                }
                return null;
            }
            var getValue = function(key) {//返回value对应的key值
                for (var i = 0; i < this.arr.length; i++) {
                    if (this.arr[i].key === key)
                        return this.arr[i].value;
                }
                return null;
            }
            var getSize = function() {//返回容器大小
                return this.arr.length;
            }
    
            var show = function() {//打印容器内容
                var string = "";
                for (var i = 0; i < this.arr.length; i++) {
                    string += (this.arr[i].key + ":" + this.arr[i].value + "
    ");
                }
                alert(string);
            }
            this.arr = new Array();
            this.remove = remove;
            this.put = put;
            this.show = show;
            this.getKey = getKey;
            this.getValue = getValue;
            this.getSize = getSize;
    
        }
    </script>
    
        <script type="text/javascript">
            var map = new Map();
            map.put("num", 1);
            map.put("red", "2");
            alert(map.getKey(1));
            alert(map.remove("num"));
            map.show();
        </script>
  • 相关阅读:
    使用typescript开发vue项目
    .sync和v-model的区别
    echarts通过dataZoom来控制默认显示固定条数数据
    ES6学习
    angular父子组件相互传值
    premiere中时间轴倍速预览及常用快捷键
    群晖Docker套件下搭建运行MSSQL
    微信的视频下载方法
    Unable to cast object of type 'System.Int32' to type 'System.String'.
    vs2017 2019莫名自动退出调试状态可以尝试一下如下的方法
  • 原文地址:https://www.cnblogs.com/carsonwuu/p/7538999.html
Copyright © 2011-2022 走看看