赞
踩
集合成员是无序的,是不重复的一组成员。
开发中可用于去除重复数据
set集合和map不一样。这里只实现了set集合的方法。
map是用哈希结构的定义来实现的,本质上也是对数组和链的结合。
方法就不介绍了,集合的定义数学都是学过的。
此处用对象的方式来实现集合
- function Set(){
- this.items={}
- }
默认set的健名是其健值
- Set.prototype.add=function(value){
- if(this.has(value)){
- return false
- }
-
- this.items[value]=value
- return true
- }
- Set.prototype.has=function(value){
- return this.items.hasOwnProperty(value)
- }
-
- Set.prototype.remove=function(value){
- if(!this.has(value)){
- return false
- }
- delete this.items[value]
- return true
- }
- Set.prototype.clear=function(){
- this.items={}
- }
- Set.prototype.size=function(){
- return Object.keys(this.items).length
- }
-
- Set.prototype.values=function(){
- return Object.keys(this.items)
- }
- Set.prototype.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;o++){
- unionSet.add(values[i])
- }
- return unionSet
- }
- Set.prototype.intersection=function(otherSet){
- var intersectionSet=new Set()
- var values=this.values()
- for(var i=0;i<values.length;i++){
- var item=values[i]
- if(otherSet.has(item)){
- intersectionSet.add(item)
- }
- }
-
- return intersectionSet
- }
- Set.prototype.difference=function(otherSet){
- var differenceSet=new Set()
- var values=this.values()
- for(var i=0;i<values.length;i++){
- var item=values[i]
- if(!otherSet.has(item)){
- differenceSet.add(item)
- }
- }
-
- return differenceSet
- }
- Set.prototype.subset=function(otherSet){
-
- var values=this.values()
- for(var i=0;i<values.length;i++){
- var item=values[i]
- if(!otherSet.has(item)){
- return false
- }
- }
-
- return true
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。