Posted on 2009-06-18 16:12
oathleo 閱讀(7929)
評(píng)論(3) 編輯 收藏 所屬分類:
Web
js 里 Object本身可以做為Map。
條件是Key只能是String
如果要用對(duì)象做為Key,這個(gè)Map可以來(lái)實(shí)現(xiàn)。
效率上由于_getIndex方法每次都要遍歷,耗時(shí)很長(zhǎng),所以通常在1:10左右
總結(jié)以上,如果Map的Key是String,最好還是用Object來(lái)實(shí)現(xiàn)。
而且用in來(lái)遍歷Map,效率上不是網(wǎng)上說(shuō)的那么差,和for()差不多
TWaver.Map = function(){
??? this._entrys = null;
??? this.initialize.apply(this, arguments);
}
TWaver.Map.prototype = {
??? initialize: function(){
??????? this._entrys = new Array();
??? },
??? put: function(key, value){
??????? if (key == null || key == undefined) {
??????????? return;
??????? }
??????? var index = this._getIndex(key);
??????? if (index == -1) {
??????????? var entry = new Object();
??????????? entry.key = key;
??????????? entry.value = value;
??????????? this._entrys[this._entrys.length] = entry;
??????? }else{
??? ??? ??? this._entrys[index].value = value;
??? ??? }??? ???
??? },
??? get: function(key){
??????? var index = this._getIndex(key);
??????? return (index != -1) ? this._entrys[index].value : null;
??? },
??? remove: function(key){
??????? var index = this._getIndex(key);
??????? if (index != -1) {
??????????? this._entrys.splice(index, 1);
??????? }
??? },
??? clear: function(){
??? ??? this._entrys.length = 0;;
??? },
??? contains: function(key){
??????? var index = this._getIndex(key);
??????? return (index != -1) ? true : false;
??? },
??? getCount: function(){
??????? return this._entrys.length;
??? },
??? getEntrys: function(){
??????? return this._entrys;
??? },
??? _getIndex: function(key){
??????? if (key == null || key == undefined) {
??????????? return -1;
??????? }
??????? var _length = this._entrys.length;
??????? for (var i = 0; i < _length; i++) {
??????????? var entry = this._entrys[i];
??????????? if (entry == null || entry == undefined) {
??????????????? continue;
??????????? }
??????????? if (entry.key === key) {//equal
??????????????? return i;
??????????? }
??????? }
??????? return -1;
??? }
}