set

概念:

区别:array是一个索引集合, set是一个键的集合

基础API

去重

格式转换

创建set

  1. // 复制
  2. new Set(setA)
  3. // array转set
  4. new Set([1, 2, 3])
  5. Set(3) {1, 2, 3}
  6. // string转set
  7. new Set('hello')
  8. Set(4) {'h', 'e', 'l', 'o'}

转array

  1. // 转array
  2. let setC = new Set([3, 4, 5, 6])
  3. [...setC]
  4. (4) [3, 4, 5, 6]
  5. let setC = new Set([3, 4, 5, 6])
  6. Array.from(setC)
  7. (4) [3, 4, 5, 6]

转string

  1. // 转string

可包含的元素数据类型

集合计算

子集 subset

如果集合A的任意一个元素都是集合B的元素,那么集合A称为集合B的子集。 符号语言:若∀a∈A,均有a∈B,则A⊆B

超集 superset

如果一个集合S2中的每一个元素都在集合S1中,且集合S1中可能包含S2中没有的元素,则集合S1就是S2的一个超集,反过来,S2是S1的子。 S1 ⊇ S2

  1. function isSuperset(set, subset) {
  2. for (let elem of subset) {
  3. if (!set.has(elem)) {
  4. return false;
  5. }
  6. }
  7. return true;
  8. }

并集union

给定两个集合A,B,把他们所有的元素合并在一起组成的集合,叫做集合A与集合B的并集,记作A∪B,读作A并B。

  1. // 方式一
  2. new Set(setA, setB)
  3. Set(4) {1, 2, 3, 4}
  4. //
  5. function union(setA, setB) {
  6. let _union = new Set(setA);
  7. for (let elem of setB) {
  8. _union.add(elem);
  9. }
  10. return _union;
  11. }

交集 intersection

集合论中,设AB是两个集合,由所有属于集合A属于集合B元素所组成的集合,叫做集合A与集合B交集,记作AB

  1. function intersection(setA, setB) {
  2. let _intersection = new Set();
  3. for (let elem of setB) {
  4. if (setA.has(elem)) {
  5. _intersection.add(elem);
  6. }
  7. }
  8. return _intersection;
  9. }

差集

对于给定的两个集合,返回一个包含所有存在于第一个集合且不存在于第二个集合的元素的新集合

  1. function difference(setA, setB) {
  2. let _difference = new Set(setA);
  3. for (let elem of setB) {
  4. _difference.delete(elem);
  5. }
  6. return _difference;
  7. }

对称差集

集合A与集合B中所有不属于A∩B的元素的集合,记为A△B

  1. function symmetricDifference(setA, setB) {
  2. let _difference = new Set(setA);
  3. for (let elem of setB) {
  4. if (_difference.has(elem)) {
  5. _difference.delete(elem);
  6. } else {
  7. _difference.add(elem);
  8. }
  9. }
  10. return _difference;
  11. }

补集

补集一般指绝对补集,即一般地,设S是一个集合,A是S的一个子集,由S中所有不属于A的元素组成的集合,叫做子集A在S中的绝对补集

相等判断

isEqual

isStrictEqual