//Map.js
//js实现的Map
//v 1.0
function Map() {
this.elements = new Array();
//得到map的大小
this.size = function() {
return this.elements.length;
}
//判断map是否为空
this.isEmpty = function() {
return (this.elements.length < 1);
}
//清空map
this.clear = function() {
this.elements = new Array();
}
//把一个键值对放入map中,
//如果该_key已经存在(containsKey(_key)返回true),
//则对应的_value替换老的值
this.put = function(_key, _value) {
var i;
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
this.elements[i].value = _value;
break;
}
}
if (i == this.elements.length) {
this.elements.push({key:_key, value:_value});
}
}
//把键等于_key的元素去掉并返回true,
//如果不存在此元素,则返回false
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 true;
}
}
return false;
}
//返回键_key对应的值,如果没有键与_key相等,则返回null
this.get = function(_key) {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
return this.elements[i].value;
}
}
return null;
}
//返回在_index位置的元素,
//如果_index小于0或者大于等于map的长度,则返回null
this.element = function(_index) {
if (_index < 0 || _index >= this.elements.length) {
return null;
}
return this.elements[_index];
}
//判断map中的键是否包含_key,
//如果包含返回true,否则返回false
this.containsKey = function(_key) {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key){
return true;
}
}
return false;
}
//判断map中的值是否包含_value,
//如果包含返回true,否则返回false
this.containsValue = function(_value) {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].value == _value){
return true;
}
}
return false;
}
//把map中的值放入数组后返回
this.values = function() {
var arr = new Array();
for (var i = 0; i < this.elements.length; i++) {
arr.push(this.elements[i].value);
}
return arr;
}
//把map中的键放入数组后返回
this.keys = function() {
var arr = new Array();
for (var i = 0; i < this.elements.length; i++) {
arr.push(this.elements[i].key);
}
return arr;
}
}
很早以前写的,欢迎大家批评指正。