JavaScript模拟字典

701 阅读1分钟

1 字典

1.1 概念

字典则是以**[键,值]**的形式来存储元素。字典也称作映射。

在字典中,存储的是[键,值]对, 其中键名是用来查询特定元素的

1.2 代码实现

function Dictionary () {
        //字典属性,存储key和value
        this.items = {}

        //原型中添加操作方法
        //字典中添加键值对(如果已经存在就是更新)
        Dictionary.prototype.set = function ( key, value ) {
            this.items[ key ] = value
        }
        //通过key判断字典中是否有该元素
        Dictionary.prototype.has = function ( key ) {
            return this.items.hasOwnProperty ( key )
        }
        //通过key移除键值对
        Dictionary.prototype.remove = function ( key ) {
            if ( this.has ( key ) ) {
                delete this.items[ key ]
                return true
            }
            return false
        }
        //通过key获取键值对
        Dictionary.prototype.get = function ( key ) {
            //先判断字典中是否存在对应的值,有就取出,没有就返回undefined
            //undefined和null不一样,null表示变量没有值,undefined表示变量被声明但未赋值
            return this.has ( key ) ? this.items[ key ] : undefined
        }
        //将字典中所有的数值,以数组的形式返回
        Dictionary.prototype.values = function () {
            let values = []
            for ( let key in this.items ) {
                if ( this.has ( key ) ) {
                    values.push ( this.items[ key ] )
                }
            }
            return values
        }
        //返回字典所包含的所有键名,以数组形式返回
        Dictionary.prototype.keys = function () {
            let keys = []
            for ( let key in this.items ) {
                if ( this.has(key ) ) {
                    keys.push ( key )
                }
            }
            return keys
        }
        //清空字典
        Dictionary.prototype.clear = function () {
            this.items = {}
        }
        //返回字典中所有元素的数量
        Dictionary.prototype.size = function () {
            return this.keys().length;
        }
        //获取字典中的items
        Dictionary.prototype.getItems = function (  ) {
            return this.items;
        }
    }

1.3 验证

  // 创建字典对象
    var dict = new Dictionary();

    // 在字典中添加元素
    dict.set("age", 18)
    dict.set("name", "Coderwhy")
    dict.set("height", 1.88)
    dict.set("address", "广州市")

    // 获取字典的信息
    console.log(dict.keys()) // age,name,height,address
    console.log(dict.values()) // 18,Coderwhy,1.88,广州市
    console.log(dict.size()) // 4
    console.log(dict.get("name")) // Coderwhy

    //删除字典中指定的元素
    dict.remove("height");
    console.log ( dict.keys () );// age,name,address

    //获得字典的items
    console.log ( "items:",dict.getItems () );

    //清空字典
    dict.clear();
    console.log ( dict.keys () );// 空数组[]