
Java中的Map是一个很实用的集合,习惯了使用Java中的Map,换别的语言没Map时感觉很不爽,以前写Flex AS代码时碰到过用要用Map的情况,不过AS其实有Dictionary字典类可以代替Java中的Map,同时也可以使用对象的属性-值形式来实现Map,在这里JS的Map实现就是使用的对象的属性-值。实现很简单,这里只是为了让Java程序员轻松的编写JS代码。
//construction
function Map() {
this.obj = new Object();
};
//add a key-value
Map.prototype.put = function(key, value) {
this.obj[key] = value;
};
//get a value by a key,if don't exist,return undefined
Map.prototype.get = function(key) {
return this.obj[key];
};
//remove a value by a key
Map.prototype.remove = function(key) {
if(this.get(key)==undefined) {
return;
}
delete this.obj[key];
};
//clear the map
Map.prototype.clear = function() {
this.obj = new Object();
};
//get the size
Map.prototype.size = function() {
var ary = this.keys();
return ary.length;
};
//get all keys
Map.prototype.keys = function() {
var ary = new Array();
for(var temp in this.obj) {
ary.push(temp);
}
return ary;
};
//get all values
Map.prototype.values = function() {
var ary = new Array();
for(var temp in this.obj) {
ary.push(this.obj[temp]);
}
return ary;
};