>[success] # 散列表js [js 的对象就是'基于哈希表结构的'](https://zhuanlan.zhihu.com/p/24291761) ~~~ 1.刚才对散列表的概念有了初步的理解,可能还是有点懵,现在用js最常见的对象来举个例子, 这个例子可能不恰当但是方便理解(实际上js对象就是散列表) 存储js对象的时候,我们的key是各种各样的数据类型,但是key的可能性是无限制,那如果系统 真的是一个萝卜一个坑来来做这件事,可能出现一个超大的储存空间,我们可以用上节的思路 如果将这些key 转换成asii码会不会实际对应的数据会减少 3.因为js 自带特效'对象',形成一个很好的实现储存的基本参数,转数字作为key,更多是没有js这种 自带buff加成的语言使用数组最为他们的基本储存参数 ~~~ * 如图 ![](https://img.kancloud.cn/b4/15/b4159bbd48fa1bba00e8350877eef880_776x486.png) * 再用js数据结构与算法书中的图更形象的来看 ![](https://img.kancloud.cn/d2/b9/d2b99c7ecba5a2ba8ccf5eee841aaae3_594x244.png) >[info] ## 实现一个自己的散列表 ~~~ 1.put(key,value):向散列表增加一个新的项(也能更新散列表)。 2.remove(key):根据键值从散列表中移除值。 3.get(key):返回根据键值检索到的特定的值。 4.loseloseHashCode: 散列函数生成散列值也就是key ~~~ >[danger] ##### 代码 ~~~ class ValuePair { constructor(key, value) { this.key = key; this.value = value; } toString() { return `[#${this.key}: ${this.value}]`; } } function defaultToString(item) { if (item === null) { return 'NULL'; } if (item === undefined) { return 'UNDEFINED'; } if (typeof item === 'string' || item instanceof String) { return `${item}`; } return item.toString(); } class HashTable{ constructor(toStrFn = defaultToString){ this.table = {} // 用来存储值的 this.toStrFn = toStrFn; } // 散列函数,可以的转换规则的函数 // 我们的规则是用ascii 码来做 loseloseHashCode(key){ if (typeof key === 'number') { return key; } const tableKey = this.toStrFn(key); // 要先将对应的类型转出字符串 let hash = 0; for (let i = 0; i < tableKey.length; i++) { hash += tableKey.charCodeAt(i); } return hash % 37; // 这可以规避操作数超过数值变量最大表示范围的风险 37不是固定的 } hashCode(key) { return this.loseloseHashCode(key); } put(key,value){ if(key!=null && value !=null){ const position = hashCode(key) this.table[position] = new ValuePair(key,value) return true } return false } // 通过key 获取值 get(key) { const valuePair = this.table[this.hashCode(key)]; return valuePair == null ? undefined : valuePair.value; } // 删除 remove(key) { const hash = this.hashCode(key); const valuePair = this.table[hash]; if (valuePair != null) { delete this.table[hash]; return true; } return false; } getTable() { return this.table; } isEmpty() { return this.size() === 0; } size() { return Object.keys(this.table).length; } clear() { this.table = {}; } toString() { if (this.isEmpty()) { return ''; } const keys = Object.keys(this.table); let objString = `{${keys[0]} => ${this.table[keys[0]].toString()}}`; for (let i = 1; i < keys.length; i++) { objString = `${objString},{${keys[i]} => ${this.table[keys[i]].toString()}}`; } return objString; } } ~~~