字典又称关联数组,映射,是一个抽象的数据结构,它包含着类似的键值有序对
字典是一种以键值对形式存储的数据结构
特点是
- 非线性存储结构
- 字典中的元素是可变的,不是必须的,键值是不重复的
- 键值是可hash的
手写字典类
class Dict {constructor() {this.data = {}this.count = 0}add(key, value) {if (!this.data[key]) {this.count++}this.data[key] = value;return true;}remove(key) {if (this.data[key]) {delete this.data[key]this.count--}return true}update(key, newVal) {if (this.data[key]) {this.data[key] = newVal;} else {this.add(key, newVal)}}find(key) {return this.data[key]}showAll() {Object.keys(this.data).forEach(key => console.log(`${key}: ${this.data[key]}`))}total() {return this.count}clear() {this.data = {}this.count = 0}has(key) {return !!this.data[key]}sort() {let result = {}Object.keys(this.data).sort().forEach(key => {result[key] = this.data[key]})this.data = result}}// 实例化一个字典类const dic = new Dict();// 添加书籍和作者dic.add('书3', '作家3');dic.add('书4', '作家4');dic.add('书2', '作家2');dic.add('书1', '作家1');dic.add('书1', '作家2');/*显示全部结果为:书3 --> 作家3书4 --> 作家4书2 --> 作家2书1 --> 作家2*/dic.showAll();// 打印字典元素总数 4console.log(dic.total())// 将字典排序dic.sort();dic.showAll();/*将排序后的字典输出结果为:书1 --> 作家2书2 --> 作家2书3 --> 作家3书4 --> 作家4*/// 删除第四本书dic.remove('书4')// 打印字典元素总数 3console.log(dic.total())
JS中的字典结构
- Object 是 键值对集合,但只能用字符串当做键
- Map提供一种完善的Hash结构,可以适用对象当键存储数据
- set/get/has/size/delete/clear
- keys/values/entries/forEach
- 键值可以hash ```javascript let map = new Map()
let a = {} let b = {}
map.set(a, 1) map.set(b, 2) console.log(map) // Map { {} => 1, {} => 2 }
最后的输出值我们可以看到是有两个值,也就是说,我们 map 中对应的 a、b 的 key 值存储的是他们的哈希地址,并不是 {} 这个空对象。所以在 map 中才会有两个值存在
3. WeakMap1. 只接受对象作为键,不包括null, 不接受其他类型的值为键1. 不可遍历1. 无法清空1. 所引用的对象都是弱引用,垃圾回收是不将此引用考虑进去的<a name="XU10R"></a>## 小结1. 字典的特点和实现方式1. js中的字典实现方式1. Map 和 WeakMap的不同<a name="RWpIR"></a>## 练习题**统计所有小于非负整数 _n_ 的质数的数量。**<br />**<br />例如:输入10<br />输出:4<br />解释:小于 10 的质数一共有 4 个 2、3、5、7```javascriptfunction count(n) {if (n <= 2) return 0;let result = new Array(n).fill(1)result[0] = 0result[1] = 0let count = 0;for (let i = 2; i < n; i++) {if (result[i] === 1) {count+=1}for (let j = 2; i * j < n; j++) {result[i * j] = 0}}return count}
