如何写一个js的hashmap

JavaScript016

如何写一个js的hashmap,第1张

使用JS写个Map很容易,但是想要HashMap估计有困难.不知道你是否只是想要个Map还是指定HashMap.以下代码是一个普通的Map:

function Map() {

var struct = function(key, value) {

this.key = key

this.value = value

}

var put = function(key, value){

for (var i = 0i <this.arr.lengthi++) {

if ( this.arr[i].key === key ) {

this.arr[i].value = value

return

}

}

this.arr[this.arr.length] = new struct(key, value)

}

var get = function(key) {

for (var i = 0i <this.arr.lengthi++) {

if ( this.arr[i].key === key ) {

return this.arr[i].value

}

}

return null

}

var remove = function(key) {

var v

for (var i = 0i <this.arr.lengthi++) {

v = this.arr.pop()

if ( v.key === key ) {

continue

}

this.arr.unshift(v)

}

}

var size = function() {

return this.arr.length

}

var isEmpty = function() {

return this.arr.length <= 0

}

this.arr = new Array()

this.get = get

this.put = put

this.remove = remove

this.size = size

this.isEmpty = isEmpty

}

var map = new HashMap()

map.put("a","1")

map.put("b","2")

遍历:

var key = map.keySet()

for (var i in key){

alert(map.get(key[i]))

注:js 中使用map,要先导入一个HashMap.js文件

没要求,引入这个文件之后,可以直接使用hashmap了

有(HashTable)。

用JS实现的数据结构,可在js的项目(前端或nodejs后端)中使用。

具体看可以看npm上的介绍,或github源码。

还有其它常用数据结构,

Stack

Queue

PriorityQueue

LinkedList

DoublyLinkedList

CircleLinkedList

HashTalbe

BinarySearchTree

RedBlackTree

UndirectedGraph

DirectedGraph

---

NPM 包:data-struct-js

>npm install data-struct-js