今天闲来无事,照着别人的例子写了一个小Demo。一眼看上去没什么难的,其实挺有意思的。
function Map(){
this.array = new Array();
var struct = function(key,value){
this.key = key;
this.value = value;
}
var put = function(key,value){
for(var i = 0 ; i < this.array.length;i++){
if(this.array[i].key == key){
this.array[i].value = value;
return;
}
}
this.array[this.array.length] = new struct(key,value);
}
var get = function(key){
for(var i = 0 ; i < this.array.length;i++){
if(this.array[i].key == key){
return this.array[i].value
}
}
return null;
}
this.put = put;
this.get = get;
}
首先,需要定义一个Map方法。在JavaScript中,方法本身也是一个对象。所以,我们可以通过new Map()的方式来得到这个对象。
其次,我们可以在Map方法里定义一些变量(array,put,get )作为Map对象的属性,并通过this关键字来指定它们的关系。
接着,我们需要定义一些方法(put,get),作为Map对象的行为。
最后,把我们定义好的方法绑定到Map的属性上就可以啦。
最重要的一件事,就是需要注意一下key和value的存储方式,是通过对象来存储的。