js 实现数据结构 -- 字典(Dictionary)

原文:

   Javascript 中学习数据结构与算法。

 

概念:

 

  集合、字典、散列表都可以存储不重复的数据。字典和我们上面实现的集合很像。

  当然,字典中的数据具有不重复的特性。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 值。

posted @   shiweiqianju  阅读(912)  评论(0编辑  收藏  举报
编辑推荐:
· 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,欢迎大家贡献代码
点击右上角即可分享
微信分享提示