字典

WARNING

字典(Dictionary)是一种以 键-值对 形式存储数据的数据结构,键和值一一对应 字典中 key 是不能重复且无序的,而 value 可以重复 JavaScript 中的 Object 类就是以字典的形式设计的

字典和映射的关系

  • 有些编程语言中称这种映射关系为字典,如 Swift 中的 Dictonary,Python 中的 dict
  • 有些编程语言中称这种映射关系为 Map,比如 ES6 的 map,Java 中的 HashMap&TreeMap 等

常用操作

  • set(key,value):向字典中添加新元素
  • get(key):通过键值查找特定的数值并返回
  • remove(key):通过使用键值来从字典中移除键值对应的数据值
  • has(key):如果某个键值存在于这个字典中,则返回 true,反之则返回 false
  • clear():将这个字典中的所有元素全部删除
  • size():返回字典所包含元素的数量。与数组的 length 属性类似
  • keys():将字典所包含的所有键名以数组形式返回
  • values():将字典所包含的所有数值以数组形式返回

字典类代码实现

封装

// 创建字典的构造函数
function Dictionay() {
	// 字典属性
	this.items = {}

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

	// 2. has方法:判断字典中是否有某个key
	Dictionay.prototype.has = function (key) {
		return this.items.hasOwnProperty(key)
	}

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

	// 4. remove方法:从字典中移除元素
	Dictionay.prototype.remove = function (key) {
		// 4.1 判断字典中是否有这个key
		if (!this.has(key)) return false

		// 4.2 从字典中删除key
		delete this.items[key]
		return true
	}

	// 5. keys方法:获取所有的keys
	Dictionay.prototype.keys = function () {
		return Object.keys(this.items)
	}

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

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

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

测试

// 创建字典对象
var dict = new Dictionay()

// 在字典中添加元素
dict.set("age", 18)
dict.set("name", "larry")
dict.set("height", 1.73)
dict.set("address", "成都市")

// 获取字典的信息
console.log(dict.keys()) // ["age", "name", "height", "address"]
console.log(dict.values()) // [18, "larry", 1.73, "成都市"]
console.log(dict.size()) // 4
console.log(dict.get("name")) // larry

// 字典的删除方法
console.log(dict.remove("height")) // true
console.log(dict.keys()) // ["age", "name", "address"]

// 清空字典
dict.clear()
console.log(dict.size()) // 0