集合是由一组无序且惟一的项组成的,在ES6中已经实现了相似的Set类。javascript
function Set() { var items = {}; //items就是集合 }
首先实现has(value)
方法,判断值是否在集合中,返回布尔值。由于集合是不容许重复元素存在的,其余方法调用这个方法判断是否值已存在。java
this.has = function(value) { return value in items; //in操做符 };
还有另一种实现方法,hasOwnProperty()
方法返回代表一个对象是否具备特定属性的布尔值。数组
this.has = function(value) { return items.hasOwnProperty(value); };
接下来实现add()
方法,向集合中添加一个新的项。学习
this.add = function(value) { if(!this.has(value)) { //判断要添加的元素是否已经存在 items[value] = value; //注意同时做为键和值保存,有利于查找这个值 return true; } return false; //添加的元素已经存在,再也不添加 };
接下来实现remove()
方法,从集合中移除一个值。this
this.remove = function(value) { if(this.has(value)) { delete items[value]; //删除对象的属性 return true; } return false; };
接下来实现clear()
方法,移除集合全部值。code
this.clear = function() { items = {}; //空对象从新赋值给它 };
接下来实现size()
方法,返回集合中有多少项。对象
第一种实现方法,使用一个length变量ip
第二种实现方法,使用Object.keys()
rem
this.size = function() { return Object.keys(items).length; //返回一个对象的全部可枚举的属性名组成的数组,但不包括原型中的属性,也不能保证按照顺序输出属性名 };
第三种实现方法,手动提取items对象的每个属性,记录个数原型
this.size = function() { var count = 0; for(var prop in items) { //遍历items的全部属性 if(items.hasOwnProperty(prop)) { //防止计数时计算到原型的属性 ++count; } } return count; };
实现values()
方法,返回全部值组成的数组。
this.values = function() { return Object.keys(items); //得到键也就得到了值(由于他们同样啊) };
var set = new Set(); set.add(1); console.log(set.values()); //['1'] console.log(set.has(1)); //true console.log(set.size()); //1 set.add(2); console.log(set.values()); //['1', '2'] set.remove(1); console.log(set.values()); //['2']
并集:两个集合,返回一个包含两个集合中全部元素的新集合
能够用来合并两个元素,并且保证了单一性。
this.union = function(otherSet) { var unionSet = new Set(); //并集结果 var values = this.values(); for(var i = 0; i < values.length; i++) { //遍历第一个集合所有放到新集合 unionSet.add(values[i]); } values = otherSet.values(); for(var i = 0; i < values.length; i++) { //遍历第二个集合所有放到新集合,使用了add方法保证了单一性 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; }
差集:元素存在于A且不存在于B中
this.difference = functiong(otherSet) { var differenceSet = new Set(); var values = this.values(); for(var i = 0; i < values.length; i++) { //遍历了A if(!otherSet.has(values[i])) { differenceSet.add(values[i]); } } return differenceSet; }
子集:A中的每个元素都在B中
this.subset = function(otherSet) { if(this.size() > otherSet.size()) return false; var values = this.values(); for(var i = 0; i < values.length; i++) { if(!otherSet.has(values[i])) { //只要有一个A中的元素不在B中,返回false return false; } } return true; }