js 实现 c# 中的数据字典(dictionary)功能

本文介绍如何在JavaScript中手动实现类似C#中的Dictionary结构,通过自定义类实现键值对的存储,提供增删改查功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在高级语言c#中存在 dictinary 这种key : value 的存储结构,但在js中没有这种现成的结构,只有数组这种结构,改编就是对数组的操作,实现 dictionary 的增删改查。看完代码你们可以试着写一个List


/**
 * 字典
 */


   function dictionary() {
      this.count=0;
        this.keys = new Array();
        this.values = new Array();
    }

    dictionary.prototype.containKey=function(key){
        var index = this.checkKeyId(key);
        if(index != -1)
        {
            return true;
        }
        return false;
    },

    dictionary.prototype.add=function(key,value){
        var index = this.checkKeyId(key);
        if(index != -1)
        {
            //print(key + " is exit");
            //alert(key + " is exit");
            console.log(key + " is exit");
            return;
        }       
        this.keys[this.count] = key;
        this.values[this.count] = value;
        ++this.count;
        // console.log(key+":"+value);
    },

    dictionary.prototype.remove=function(key){
        var index = this.checkKeyId(key);
        if(-1==index)
        {
            console.log(key+" does not exist");
            return;
        }
        this.keys.splice(index,1);
        this.values.splice(index,1);
        --this.count;
    }

    dictionary.prototype.get=function(key){
        var index = this.checkKeyId(key);
        if(-1==index)
        {
            console.log(key+" does not exist:");
            return null;
        }
        return this.values[index];
    }

    dictionary.prototype.checkKeyId=function(key){
        for(i=0;i<this.count;i++)
        {
            if(key==this.keys[i])
            {
                return i;
            }
        }
        return -1;
    }

    dictionary.prototype.getNameByIndex = function(index)
    {
        return this.keys[index];
    }

module.exports = dictionary;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值