JavaScript中没有类似Java中的Map集合类的实现,自己做了简单实现,如下:
function Map() {
this.elements = new Array();
this.size=function(){
return this.elements.length;
};
this.isEmpty=function(){
return (this.elements.length < 1);
};
this.clear=function(){
this.elements=new Array();
};
this.put=function(_key,_value) {
if (!this.containsKey(_key)) {
this.elements.push({
key:_key,value:_value
});
} else {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].key === _key) {
this.elements[i].value = _value;
}
}
}
};
this.remove=function(_key) {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].key === _key) {
this.elements.splice(i, 1);
return;
}
}
};
this.get=function(_key) {
try {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].key === _key) {
return this.elements[i].value;
}
}
} catch(e) {
return null;
}
return null;
};
this.containsKey=function(_key) {
try {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].key===_key) {
return true;
}
}
} catch (e) {
return false;
}
return false;
};
this.entryArray = function() {
var eArr = [];
try {
for (var i = 0; i < this.elements.length; i++) {
eArr.push(new Entry(this.elements[i].key, this.elements[i].value));
};
} catch (e) {
return eArr;
}
return eArr;
}; function Entry(key, value) {
this.key = key;
this.value = value;
}
}
<END>