javascript 자바스크립트에서 hashmap 사용하기
javascript 에서 좋은 방법은 아니지만, 맵을 사용하고 싶을 때가 있다.
java에서 사용하던 방식대로 사용하려면 다음과 같은 함수를 정의하고 사용하면 된다고 한다..
(구글링에서 찾았는데, 출처가 기억이 안난다...죄송 ㅠ)
Map = function(){
this.map = new Object();
};
Map.prototype = {
put : function(key, value){
this.map[key] = value;
},
get : function(key){
return this.map[key];
},
containsKey : function(key){
return key in this.map;
},
containsValue : function(value){
for(var prop in this.map){
if(this.map[prop] == value) return true;
}
return false;
},
isEmpty : function(key){
return (this.size() == 0);
},
clear : function(){
for(var prop in this.map){
delete this.map[prop];
}
},
remove : function(key){
delete this.map[key];
},
keys : function(){
var keys = new Array();
for(var prop in this.map){
keys.push(prop);
}
return keys;
},
values : function(){
var values = new Array();
for(var prop in this.map){
values.push(this.map[prop]);
}
return values;
},
size : function(){
var count = 0;
for (var prop in this.map) {
count++;
}
return count;
}
};
위 함수들을 선언해주고, 다음과 같이 java에서 처럼 사용하면 된다.
var map = new Map();
map.put("id", "test");
map.get("id");