js實現map集合
阿新 • • 發佈:2019-01-28
map集合方式一:
var hashMap ={
Set:function(key,value){this[key]=value},
Get:function(key){return this[key]},
Contains:function(key){return this.Get(key)==null?faise:true},
Remove:function(key){delete this[key]}
}
使用方式舉例:
hashMap.Set("aa","bb");
hashMap.Get("aa");
hashMap.Remove("aa");
map集合方式二:
var nameAndStatuskeys = new Array();
var nameAndStatusdata = new Array();//存放裝置名字和狀態的List集合
function addMap(key,value){
if(nameAndStatusdata[key] == null){
nameAndStatuskeys.push(value);
}
nameAndStatusdata[key] = value;
}
function getMap(key){
return nameAndStatusdata[key];
}
function removeMap(key){
return delete nameAndStatusdata[key]
}
使用方式舉例:
addMap("aa","bb");
getMap("aa");
removeMap("aa");
map集合方式三
function Map(){
this.container = new Object();
}
Map.prototype.put = function(key, value){
this.container[key] = value;
}
Map.prototype.get = function(key){
return this.container[key];
}
Map.prototype.keySet = function () {
var keyset = new Array();
var count = 0;
for (var key in this.container) {
// 跳過object的extend函式
if (key == 'extend') {
continue;
}
keyset[count] = key;
count++;
}
return keyset;
}
Map.prototype.size = function() {
var count = 0;
for (var key in this.container) {
// 跳過object的extend函式
if (key == 'extend'){
continue;
}
count++;
}
return count;
}
Map.prototype.remove = function(key) {
delete this.container[key];
}
Map.prototype.toString = function(){
var str = "";
for (var i = 0, keys = this.keySet(), len = keys.length; i < len; i++) {
str = str + keys[i] + "=" + this.container[keys[i]] + ";\n";
}
return str;
}
使用方式舉例:
var markersMap = new Map();
markersMap.put("aa","bb");
markersMap.get("aa");
markersMap.remove("aa");
var array = markersMap.keySet();
for(var i in array) {
markersMap.remove(array[i]);
}