数据结构与算法8:用JavaScript 实现 字典 结构

本文将探讨如何使用JavaScript来实现字典结构,包括set、has、remove、get、keys、values、size和clear等核心方法,帮助你理解和操作字典数据结构。

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

常用方法

  • set(key, value) 添加键值对
  • has(key)判断字典中是否有某个key
  • remove(key)从字典中移除元素remove
  • get(key) 根据key去获取value
  • keys() 获取多有的keys
  • values()获取所有的value
  • size() 查看大小
  • clear()方法
// 封装字典
// 创建字典的构造函数
function Dictionary() {
    // 字典属性
    this.items = {}

    // 字典操作方法
    // 1 添加键值对
    Dictionary.prototype.set = function (key, value) {  
        this.items[key] = value;
    }

    // 2 判断字典中是否有某个key
    Dictionary.prototype.has = function (key) {
        return this.items[key] != null
    }

    // 3 从字典中移除元素remove
    Dictionary.prototype.remove = function (key) {  
        delete this.items[key]
        return true
    }

    // 4 根据key去获取value 
    Dictionary.prototype.get = function (key) {  
        return this.has(key) ? this.items[key] : undefined
    }

    // 5 获取多有的keys
    Dictionary.prototype.keys = function () {  
        return Object.keys(this.items)
    }

    // 6 获取所有的value
    Dictionary.prototype.values = function () {  
        return Object.values(this.items)
    }

    // 7 size方法
    Dictionary.prototype.size = function () {  
        // return Object.keys(this.items).length
        return this.keys().length
    }

    // 8 clear方法
    Dictionary.prototype.clear = function () {  
        this.items = {}
    }
}

// export function Dictionary()
// export {Dictionary}
// module.exports = {Dictionary}

// // 测试
// // 插入值
// let dic = new Dictionary();
// dic.set("a", 123);
// dic.set("b", 456);
// dic.set("c", 789);
// dic.set("d", "qwe");
// console.log(dic);

// console.log(dic.has("a"));
// console.log(dic.has("f"));
// console.log(dic.has(999));

// console.log(dic.get("a"));
// console.log(dic.get(999));

// console.log(dic.keys());
// console.log(dic.size());

// console.log(dic.values());

// dic.remove("d");
// console.log(dic.values());

// dic.clear();
// console.log(dic.values());
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值