实现思路
文章图片
完整可运行代码
【【数据结构】JavaScript HashTable 实现】
文章图片
class HashTable {
constructor() {
this.tableSize= 10000007
this.table = new Array(this.tableSize).fill(0)
}
_hash(s) {
let n = 1
let f = 1
let arr = s.split('')
for(let i in arr) {
n += arr[i].charCodeAt() * f
f *= 10
}
return n
}
_index(k) {
return this._hash(k)
}
_insert_at_index(index, k, v) {
// console.log(index)
// console.log(this.table[index])
let tmp = this.table[index]
let data = https://www.it610.com/article/[k, v]
// console.log('tmp ', tmp)
// console.log(data)
if(tmp === 0) {
this.table[index] = [data]
} else {
this.table[index].push([data])
}
}
set(k, v) {
let index = this._index(k)
this._insert_at_index(index, k, v)
}
//
get(k) {
let index = this._index(k)
// console.log('index ', index)
let tmp = this.table[index]
// console.log('tmp ', tmp)
if(tmp instanceof Array) {
for(let kv in tmp) {
if(tmp[kv][0] === k) {
return tmp[kv][1]
}
}
}
return null
}
}
//
let ht = new HashTable()
let names = ['tao', 'gua', 'wu']for(let i in names) {
let v = i
ht.set(names[i], v)
console.log('set ', names[i], v)
}
for(let j in names) {
let v = ht.get(names[j])
console.log('get ', names[j], v)
}
推荐阅读
- 【数据结构】JavaScript Binary Tree 实现
- map|在vue项目中引入高德地图并使用
- vue.js|在vue项目中引入高德地图
- UE4|[UE4 笔记]使用webbrowser获取网页图片原始大小(UE4获取Js相关信息的思路)
- apipost脚本使用讲解一~全局变量
- 前端面试题|【前端面试题】防抖与节流-js
- 前端|JavaScript 事件 -- 默认行为,限制范围拖拽
- 【JavaScript】柯里化
- 青龙面板-来自保姆的喂饭|(九)青龙Tools 正式版/前端网页提交+后台管理/适用于所有场景/开饭开饭开饭 【2022年6月15日】【更新】