js 实现数据结构 -- 字典(Dictionary)
原文:
概念:
集合、字典、散列表都可以存储不重复的数据。字典和我们上面实现的集合很像。
当然,字典中的数据具有不重复的特性。js 中 Object 的键值对 key: value 的形式就是字典的实现,所以字典通常也称为映射。
实现一个简单的字典类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | class Dictionary { constructor() { this .items = {} } set(key, value) { this .items[key] = value; } get(key) { return this .items[key]; } remove(key) { delete this .items[key]; } get keys() { return Object.keys( this .items); } get values() { // es7 提供的 Object.values 方法 // return Object.values(this.items); // 或者循环输出 return Object.keys( this .items).reduce((r, c, i) => { r.push( this .items[c]); return r; }, []) } } // 使用 let dictionary = new Dictionary(); dictionary.set( 'Gandalf' , 'gandalf@email.com' ) dictionary.set( 'John' , 'johnsnow@email.com' ) dictionary.set( 'Tyrion' , 'tyrion@email.com' ) console.log(dictionary) console.log(dictionary.keys) console.log(dictionary.values) console.log(dictionary.items) |
结构比较简单,需要注意的可能点是 key 相同的时候,后面添加的会覆盖前面的 value 值。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码