JS自定義乙個Map類

2021-08-08 14:00:43 字數 2910 閱讀 2243

例子1

//定義簡單map

function getmap() ;  

map_.get = function(key) ;  

map_.remove = function(key) ;  

map_.keyset = function()  

}  if(ret == "") else  

};  

return map_;  

}var map = getmap();

map.put("395","12,21,52,89,35");

map.put("396","121111,2222221,5333332,8444449,3555555");

alert(map.get("395"));//輸出:12,21,52,89,35

alert(map.keyset()); //輸出:395,396

例子2

function hashmap();

}hashmap.prototype = ,

get : function(key)

return null;

},remove : function(key)

return false;

},removeall : function();

},keyset : function()

return _keys;}};

hashmap.prototype.constructor = hashmap;

var hashmap = new hashmap();

hashmap.put('key' ,'value');

hashmap.put('key1' ,'value');

console.log(hashmap.get('key'));

console.log(hashmap.keyset());

console.log(hashmap.remove('key'));

console.log(hashmap.keyset());

例子3

function map() ;

//判斷map是否為空

this.isempty = function() ;

//刪除map所有元素

this.clear = function() ;

//向map中增加元素(key, value) 

this.put = function(_key, _value) );

};//刪除指定key的元素,成功返回true,失敗返回false

this.removebykey = function(_key)

}} catch (e)

return bln;

};//刪除指定value的元素,成功返回true,失敗返回false

this.removebyvalue = function(_value)

}} catch (e)

return bln;

};//刪除指定value的元素,成功返回true,失敗返回false

this.removebyvalueandkey = function(_key,_value)

}} catch (e)

return bln;

};//獲取指定key的元素值value,失敗返回null

this.get = function(_key)

}} catch (e)

return false;

};//獲取指定索引的元素(使用element.key,element.value獲取key和value),失敗返回null

this.element = function(_index)

return this.elements[_index];

};//判斷map中是否含有指定key的元素

this.containskey = function(_key)

}} catch (e)

return bln;

};//判斷map中是否含有指定value的元素

this.containsvalue = function(_value)

}} catch (e)

return bln;

};//判斷map中是否含有指定value的元素

this.containsobj = function(_key,_value)

}} catch (e)

return bln;

};//獲取map中所有value的陣列(array)

this.values = function()

return arr;

};//獲取map中所有value的陣列(array)

this.valuesbykey = function(_key)

}return arr;

};//獲取map中所有key的陣列(array)

this.keys = function()

return arr;

};//獲取key通過value

this.keysbyvalue = function(_value)

}return arr;

};//獲取map中所有key的陣列(array)

this.keysremoveduplicate = function()  

}if(flag)

}return arr;};}

第二種好用,本人推薦使用第二種

js自定義類

一 三種方式模擬 類 1 工廠方式 function cat return cat 使用 var mycat cat 2 建構函式方式 function cat 使用 var mycat new cat 3 原型方式 該方式利用了物件的prototype屬性。首先用空函式建立類名,然後所有的屬性和方...

自定義乙個vector向量類

c 標準模板庫stl給出了vector,list,deque,stack,set,map等模板類,平時我們直接使用居多,對於類內部怎麼實現不在意。現在以向量類vector為例,簡單自定義 其uml vetor 陣列名ele t 陣列目前大小size int 陣列容量cap int vector 用指...

自定義乙個python日誌類

本文介紹如何寫乙個python日誌類,用來輸出不同級別的日誌資訊到不同的日誌檔案裡。1 將不同級別的日誌輸出到不同的日誌檔案裡,方便自己排查問題。2 生成的日誌放在專案根目錄的logs資料夾裡 3 日誌類支援debug,info,warning,error,critical五種級別日誌。4 日誌輸出...