博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JS数据结构-集合-常见操作
阅读量:331 次
发布时间:2019-03-04

本文共 2275 字,大约阅读时间需要 7 分钟。

一.集合

  • 集合通常是由一组无序的,不重复的元素构成
  • 集合可以看做是特殊的数组
  • 特殊之处在于里面的元素没有顺序,也不能重复
  • 没有顺序意味着不能通过下标值进行访问,不能重复意味着相同的对象在集合中只会存在一份

二.集合的封装

function Set(){
// 属性 this.items = {
} // 方法}
  • add方法:在集合中添加元素
// add方法Set.prototype.add = function(value){
// 判断当前集合中是否已经包含了该元素(使用Set的has方法) if(this.has(value)){
return false } // 将元素添加到集合中 this.items[value] = value return true}
  • has方法:判断集合中是否存在该元素
Set.prototype.has = function(value){
return this.items.hasOwnProperty(value) // 对象结构中自带的方法}
  • remove方法:删除集合中的元素,注意集合中的元素不能通过下标值访问!
Set.prototype.remove = function(value){
// 判断该集合中是否包含该元素 if(!this.has(value)){
return false } // 将元素从属性中删除 delete this.items[value] return true}
  • clear方法:清空集合
Set.prototype.clear = function(){
this.items = {
}}
  • size方法:返回集合中元素的个数
Set.prototype.size = function(){
return Object.keys(this.items).length}
  • 获取集合中所有的值
Set.prototype.values = function(){
return Object.keys(this.items)}

三.集合间操作

通常包括四种操作:并集、交集、差集、子集

  • 并集操作union
// this: 集合对象A// otherSet: 集合对象BSet.prototype.union = function(otherSet){
// 创建新的集合 var unionSet = new Set() // 将A集合中所有的元素添加到该集合中 var values = this.values() for(var i = 0 ; i < values.length ; i++){
unionSet.add(values[i]) } // 取出B集合中的元素,判断是否需要加到新集合 values = otherSet.values() for(var i = 0 ; i < values.length ; i++){
unionSet.add(values[i]) } return unionSet}
  • 交集操作intersection
Set.prototype.intersection = function(otherSet){
// 创建新的集合 var intersectionSet = new Set() // 从A集合中取出一个个元素,判断是否同时存在于集合B中,若存在则放入新集合中 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}
  • 差集操作difference
Set.prototype.difference = function(otherSet){
// 创建新的集合 var differenceSet = new Set() // 取出A集合一个个元素,判断是否同时存在B集合中,若不存在B中,则添加到新集合中 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}
  • 子集操作subset
Set.prototype.subset = function(otherSet){
// 遍历集合A中所有的元素,如果发现集合A中的元素在集合B中不存在,那么false // 如果遍历完了整个A集合,依然没有返回false,则返回true var values = this.values() for(var i = 0; i < values.length ; i++){
var item = values[i] if(!otherSet.has(item)){
return false } } return true}

转载地址:http://lhze.baihongyu.com/

你可能感兴趣的文章