有人回复说需要添加做验证,我觉得不必了,如果添加的值和之前的一样就直接替换好了,如果希望不被replace,直接在添加新对象之前用contain判断一次就可以了,毕竟在我的实现中已不是完全在模拟Set了,目前更倾向于设计一个更高效和强大的集合类function Map(){ this.obj = {}; this.count = 0; } Map.prototype.put = function(key, value){ var oldValue = this.obj[key]; if(oldValue == undefined){ this.count++; } this.obj[key] = value; return oldValue; } Map.prototype.get = function(key){ return this.obj[key]; } Map.prototype.remove = function(key){ var oldValue = this.obj[key]; if(oldValue != undefined){ this.count--; delete this.obj[key]; } return oldValue; } Map.prototype.size = function(){ return this.count; } function Set(getKey){ this.map = new Map(); this.getKey = getKey; } Set.prototype.add = function(value){ var key = this.getKey(value); this.map.put(key, value); } Set.prototype.remove = function(value){ var key = this.getKey(value); this.map.remove(key); } Set.protorype.getAll=function(){ tempArray=new Array(); for(var i in this.obj){ tempArray.push(i); } return tempArray; } Set.prototype.size = function(){ return this.map.size(); } 还有一个朋友的实现和我最初的差不多,但是remove方法相当有创意,用正则表达式来删除 Collection.prototype.remove=function(o){ var _var = this.chain; this.table[o.id]=null; var re = new RegExp("(^["+o.id+"]$)|(^["+o.id+"][,])|([,]["+o.id+"]$)","g"); var s = "["+this.chain.toString().replace(re,"").replace(","+o.id+",",",")+"]"; this.chain=eval(s) }
原文地址