ES6简单map结构实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class myMap{
constructor(obj){
this.obj = {}
this.length = 0
if(Array.isArray(obj)){
obj.every((item, index, arr) => {
if(Array.isArray(item)){
this.obj[item[0]] = item[1]
this.length += 1
return true
}else{
this.obj = {}
this.length = 0
return false
}
})
}
}

has(key){
return this.obj.hasOwnProperty(key)
}

size(){
return this.length
}

get(key){
if(this.has(key)){
return this.obj[key]
}
}

set(key, value){
if(this.has(key)){
this.obj[key] = value
}else{
this.obj[key] = value
this.length += 1
}
return this
}

keys(){
return Object.keys(this.obj)
}

values(){
return Object.values(this.obj)
}

entries(){
return Object.entries(this.obj)
}

delete(key){
if(this.has(key)){
this.length -= 1
delete this.obj[key]
}
return this
}

clear(){
this.obj = {}
this.length = 0
return this
}
}

let my_Map = new myMap()
my_Map.set('foo', true).set('foo2', false).set('foo2', 1)
console.log(my_Map);

let map = new Map()
map.set('foo', true)
map.set('foo2', false)
console.log(map);