• JavaScript 模拟 Dictionary


    function Dictionary() {
        var items = {};
    
        //判断是否包含Key值
        this.has = function(key) {
            return key in items;
        };
    
        //赋值,添加键值对
        this.set = function(key, value) {
            items[key] = value;
        };
    
        //移除Key值
        this.remove = function(key) {
            if (this.has(key)) {
                delete items[key];
                return true;
            }
            return false;
        };
    
        //通过Key值获取Value值
        this.get = function(key) {
            return this.has(key) ? items[key] : undefined;
        };
    
        //获取所有的Key值
        this.keys = function() {
            var keys = [];
            for (var k in items) {
                keys.push(k);
            }
            return keys;
        };
    
        //获取所有的Value值
        this.values = function() {
            var values = [];
            for (var k in items) {
                if (this.has(k)) {
                    values.push(items[k]);
                }
            }
            return values;
        };
    
        //初始化键值对
        this.clear = function() {
            items = {};
        };
    
        //获取键值对的个数
        this.size = function() {
            var count = 0;
            for (var prop in items) {
                if (items.hasOwnProperty(prop)) {++count;
                }
            }
            return count;
        };
    
        //获取所有的键值对
        this.getItems = function() {
            return items;
        };
    } 

    使用方法如下图:

  • 相关阅读:
    正则表达式 1
    14 同步 1
    14 线程属性
    14 线程状态
    14 线程
    window.location.hostname与 window.location.host 区别
    泛型 的通配符类型 extends super
    svn拷贝一个项目作为新项目
    List Collections sort
    && 和 || 逻辑运算符
  • 原文地址:https://www.cnblogs.com/ZhangJiXuan/p/9813754.html
Copyright © 2020-2023  润新知