字典的概念和用途

# 字典的概念和用途

  • 字典是以键值对的形式存储的。

  • JavaScript 中的 Object 类就是以字典的形式设计的。

# 字典的代码实现

function Dictionary() {
  this.dataStore = new Array();
  this.add = add;
  this.find = find;
  this.remove = remove;
  this.count = count;
  this.clear = clear;
  this.showAll = showAll;
}

// 向字典中添加元素
function add(key, value) {
  this.dataStore[key] = value;
}

// 查询字典中的某个元素
function find(key) {
  return this.dataStore[key];
}

// 删除字典中的某个元素
function remove(key) {
  delete this.dataStore[key];
}

// 查询字典中的元素个数
function count() {
  return Object.keys(this.dataStore).length;
}

// 清空字典
function clear() {
  var dataKeys = Object.keys(this.dataStore);
  for (var key in dataKeys) {
    delete this.dataStore[dataKeys[key]];
  }
}

// 打印整个字典信息
function showAll() {
  var dataKeys = Object.keys(this.dataStore);
  for (var key in dataKeys) {
    console.log(dataKeys[key] + " -> " + this.dataStore[dataKeys[key]]);
  }
}

var goods = new Dictionary();
goods.add("first", 456);
goods.add("second", 145);
goods.add("third", 954);
console.log(goods.find("second"));
goods.showAll();
console.log(goods.count());
goods.remove("second");
goods.showAll();
goods.clear();
console.log(goods.count());
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
45
46
47
48
49
50
51
52
53
54
55
56
57

# 字典的另一种实现

var Dictionary = function() {
  var items = {};

  // 检查键是否存在
  this.has = function(key) {
    // return items.hasOwnProperty(key)
    return key in items;
  };

  this.set = function(key, value) {
    items[key] = value;
  };

  this.delete = function(key) {
    if (this.has(key)) {
      delete items[key];
      return true;
    }
    return false;
  };

  this.get = function(key) {
    if (this.has(key)) {
      return items[key];
    }
    return undefined;
  };

  this.getItems = function() {
    return items;
  };
};
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
上次更新时间: 2026年06月03日 02:13:09