数据结构——集合(JavaScript)

来源:互联网 发布:headfirst python pdf 编辑:程序博客网 时间:2024/06/06 11:36

初始化集合

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){//从集合移除一个值        delete items[value];//这里要注意不能写成delete value        return true;    }    this.clear = function(){//移除集合中的所有项         items = {};    }    this.size = function(){//返回集合所包含元素的数量        return Object.keys(items).length;    }    this.values = function(){        return Object.keys(items);    }}

使用集合:

var nset = new Set();nset.add(1);nset.add(2);nset.add(3);

控制台输出:

这里写图片描述

集合操作

this.union = function(oterSet){//求并集//思路:将oterSet的值全部给unionSet,然后将items中的值添加到unionSet中,这里的add函数已经判断过该属性是否在set中存在,可以直接借用    var unionSet = oterSet;    for(var i=0; i<this.values().length; i++){        unionSet.add(this.values()[i]);    }    return unionSet;}

使用:

var nset = new Set();nset.add(1);nset.add(2);nset.add(3);var nset2 = new Set();nset2.add(4);nset2.add(2);nset2.add(3);console.log(nset.union(nset2).values());

控制台输出:(同时我们输出nset与nset2)
这里写图片描述

问题来了:
nset2变了,这是为什么呢?我们回过头来看,会发现在方法union中,var unionSet = oterSet;两个变量同时指向同一个Set数据结构,当函数内部对unionSet进行操作的时候,指向的内容就随之改变了,所以nset2的数值会发生变化。这一切皆是因为JavaScript中对象的指向是地址。

//更改后this.union = function(oterSet){//求并集    var unionSet = new Set();    for(var i=0; i<this.values().length; i++){        unionSet.add(this.values()[i]);    }    for(var i=0; i<oterSet.values().length; i++){        unionSet.add(oterSet.values()[i]);    }    return unionSet;}//交集、差集、子集同理this.intersection = function(oterSet){//交集    var intersectionSet = new Set();    for(var i = 0; i<this.values().length; i++){//注意这里判断处理的都是values()之后的数组        if(this.has(oterSet.values()[i])){            intersectionSet.add(oterSet.values()[i]);        }    }    return intersectionSet;}this.difference = function(oterSet){//并集    var differenceSet = new Set();    var value = this.values();    for(var i = 0; i < value.length; i++){        if(!oterSet.has(value[i])){            differenceSet.add(value[i]);        }    }    return differenceSet;}this.subset = function(otherSet){//子集    if(this.size() <= otherSet.size()){        var value = this.values();        for(var i = 0; i<value.length; i++){            if(!otherSet.has(value[i])){                return false;            }        }        return true;    }else{        return false;    }}

Set()集合的使用

var nset = new Set();nset.add(1);nset.add(2);nset.add(3);var nset2 = new Set();nset2.add(4);nset2.add(2);nset2.add(3);var nset3 = new Set();nset3.add(2);nset3.add(3);console.log(nset.union(nset2).values());console.log(nset.intersection(nset2).values());console.log(nset3.subset(nset2));console.log(nset3.subset(nset));

控制台输出:

这里写图片描述

0 0
原创粉丝点击