JavaScript数据结构-集合|8月更文挑战

244 阅读2分钟

这是我参与8月更文挑战的第7天,活动详情查看:8月更文挑战

1. 集合简介

集合(set)是一种包含不同元素的数据结构。集合中的元素称为成员。集合的两个最重要特性是:首先,集合中的成员是无序的;其次,集合中不允许相同成员存在。

2. 集合的定义

  • 不包含任何成员的集合称为空集,全集则是包含一切可能成员的集合。
  • 如果两个集合的成员完全相同,则称两个集合相等。
  • 如果一个集合中所有的成员都属于另外一个集合,则前一集合称为后一集合的子集。

3. 集合的操作

  • 并集:将两个集合中的成员进行合并,得到一个新集合。
  • 交集:两个集合中共同存在的成员组成一个新的集合。
  • 补集:属于一个集合而不属于另一个集合的成员组成的集合。

4. 构造集合的代码

function Set() { 
  this.data = [];
  this.add = add;
  this.remove = remove; 
  this.size = size; 
  this.union = union; 
  this.intersect = intersect; 
  this.subset = subset; 
  this.difference = difference; 
  this.show = show; 
}
  • add() 方法将数据存储到数组前,先要确保数组中不存在该数据。
function add(data) { 
  if (this.data.indexOf(data) < 0) { 
    this.data.push(data); 
    return true;
  }else {
    return false;
  } 
}
  • remove() 删除成员元素
function remove(data) {
    var pos = this.data.indexOf(data);
    if (pos > -1) {
        this.data.splice(pos,1);
        return true;
    }
    else {
        return false;
    }
}
  • show()方法可以显示集合中的成员
function show() {
    return this.data;
}
  • contains()方法检查一个成员是否属于该集合
function contains(data) {
    if (this.data.indexOf(data) > -1) {
        return true;
    }
    else {
        return false;
    }
}
  • union() 方法执行并集操作,将两个集合合并成一个。
function union(set) {
  var tempSet = new Set();
  for (var i = 0; i < this.data.length; ++i) {
    tempSet.add(this.data[i]);
  }
  for (var i = 0; i < set.data.length; ++i) {
    if (!tempSet.contains(set.data[i])) {
      tempSet.data.push(set.data[i]);
    }
  } 
  return tempSet;
}
  • intersect() 方法求两个集合的交集
function intersect(set) {
  var tempSet = new Set();
  for (var i = 0; i < this.data.length; ++i) {
    if (set.contains(this.data[i])) {
      tempSet.add(this.data[i]);
    }
  }
  return tempSet;
}
  • difference()方法 该集合包含的是那些属于第一个集合但不属于第二个集合的成员
function difference(set) {
  var tempSet = new Set();
  for (var i = 0; i < this.data.length; ++i) {
    if (!set.contains(this.data[i])) {
      tempSet.add(this.data[i]);
    }
  } return tempSet;
}

5. javascript的ES6也有Set的数据结构方法

let nums = new Set(['1'])
// 判断是否存在
console.log(nums.has('1')) // true
// 数量
console.log(nums.size) // 1
// 新增
animals.add('2')
console.log(nums) // Set { '1', '2' }
// 删除
animals.delete('1')
console.log(nums) // Set { '2' }
// 清空
animals.clear()
console.log(nums) // Set {}