首页 > 代码库 > javascript集合的交,并,补,子集的操作实现
javascript集合的交,并,补,子集的操作实现
可能新的ECMA规范里已有了这些的实现,
但能自己从头开始实现,感觉也非常不错的哟。。。
function Set() { var items = {}; this.has = function(value){ return items.hasOwnProperty(value); }; this.add = function(value){ if (!this.has(value)){ items[value] = value; return true; } return false; }; this.remove = function(value){ if (this.has(value)) { delete items[value]; return true; } return false; }; this.clear = function(){ items = {}; }; this.size = function(){ var count = 0; for (var prop in items){ if(items.hasOwnProperty(prop)){ ++count; } } return count; }; this.values = function(){ var keys = []; for (var key in items){ keys.push(key); } return keys; }; this.union = function(otherSet){ var unionSet = new Set(); var values = this.values(); for(var i=0; i<values.length; i++){ unionSet.add(values[i]); } var values = otherSet.values(); for(var i=0; i<values.length; i++){ unionSet.add(values[i]); } return unionSet; }; this.intersection = function(otherSet){ var intersectionSet = new Set(); var values = this.values(); for(var i=0; i<values.length; i++){ if (otherSet.has(values[i])){ intersectionSet.add(values[i]); } } return intersectionSet; }; this.difference = function(otherSet){ var differenceSet = new Set(); var values = this.values(); for(var i=0; i<values.length; i++){ if(!otherSet.has(values[i])){ differenceSet.add(values[i]); } } return differenceSet; }; this.subset = function(otherSet){ if (this.size() > otherSet.size()){ return false; } else { var values = this.values(); for(var i=0; i<values.length; i++){ if(!otherSet.has(values[i])){ return false; } } return true; } }}var set = new Set();set.add(1);console.log(set.values()); //输出["1"]console.log(set.has(1)); //输出trueconsole.log(set.size()); //输出1set.add(2);console.log(set.values()); //输出["1", "2"]console.log(set.has(2)); //trueconsole.log(set.size()); //2set.remove(1);console.log(set.values()); //输出["2"]set.remove(2);console.log(set.values()); //输出[]var setA = new Set();setA.add(1);setA.add(2);setA.add(3);var setB = new Set();setB.add(3);setB.add(4);setB.add(5);setB.add(6);var unionAB = setA.union(setB);console.log(unionAB.values());var setA = new Set();setA.add(1);setA.add(2);setA.add(3);var setB = new Set();setB.add(2);setB.add(3);setB.add(4);var intersectionAB = setA.intersection(setB);console.log(intersectionAB.values());var setA = new Set();setA.add(1);setA.add(2);setA.add(3);var setB = new Set();setB.add(2);setB.add(3);setB.add(4);var differenceAB = setA.difference(setB);console.log(differenceAB.values());var setA = new Set();setA.add(1);setA.add(2);var setB = new Set();setB.add(1);setB.add(2);setB.add(3);var setC = new Set();setC.add(2);setC.add(3);setC.add(4);console.log(setA.subset(setB));console.log(setA.subset(setC));
javascript集合的交,并,补,子集的操作实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。