• 集合是由一组无序且唯一的项组成。
  1. add 添加
  2. remove 删除
  3. has 是否在集合中
  4. clear 清空
  5. size 集合的元素数量
  6. values 返回一个包含所有值的数组
  7. union 并集
  8. intersction 交集
  9. difference 差集
  10. subset 子集

js 实现集合

  1. function Set(){
  2. // 元素对象
  3. var items = {};
  4. // 是否存在
  5. this.has = function(value){
  6. return items.hasOwnProperty(value)
  7. }
  8. // 添加元素
  9. this.add = function(value){
  10. // 如果集合中没有这个元素则添加它
  11. if(!this.has(value)){
  12. items[value] = value;
  13. return true;
  14. } else{
  15. return false;
  16. }
  17. }
  18. // 删除
  19. this.remove = function(value){
  20. if(this.has(value)){
  21. delete items[value];
  22. return true;
  23. }else{
  24. return false;
  25. }
  26. }
  27. // 清除
  28. this.clear = function(){
  29. items = {};
  30. }
  31. // 元素个数
  32. this.size = function(){
  33. return Object.keys(items).length;
  34. }
  35. // 集合的值
  36. this.values = function(){
  37. return Object.keys(items);
  38. }
  39. // 并集
  40. this.union = function(otherset){
  41. // 实例化一个新的集合
  42. var unionset = new Set();
  43. // 把当前集合合并到新集合中
  44. var values = this.values();
  45. for(let i = 0;i<values.length;i++){
  46. unionset.add(values[i])
  47. }
  48. // 要被合并的集合也添加到新集合中
  49. values = otherset.values();
  50. for(let i = 0;i<values.length;i++){
  51. unionset.add(values[i])
  52. }
  53. return unionset;
  54. }
  55. // 交集
  56. this.intersction = function(otherset){
  57. var intersctionSet = new Set();
  58. var values = this.values();
  59. for(let i = 0;i<values.length;i++){
  60. if(otherset.has(values[i])){
  61. intersctionSet.add(values[i])
  62. }
  63. }
  64. return intersctionSet;
  65. }
  66. // 差集
  67. this.difference = function(otherset){
  68. var differenceSet = new Set();
  69. var values = this.values();
  70. for(let i= 0;i<values.length;i++){
  71. if(!otherset.has(values[i])){
  72. differenceSet.add([values[i]])
  73. }
  74. }
  75. return differenceSet;
  76. }
  77. // 子集
  78. this.subset = function(otherset){
  79. // 如果当前的元素个数大于otherset的元素个数,当前集合就不是其他集合的子集。
  80. if(this.size()>otherset.size())return false;
  81. var values = this.values();
  82. for(let i =0;i<values.length;i++){
  83. if(!otherset.has(values[i])) return false;
  84. }
  85. return true;
  86. }
  87. }
  88. var setA = new Set();
  89. setA.add(1);
  90. setA.add(12);
  91. setA.add(14);
  92. var setB = new Set();
  93. setB.add(1);
  94. setB.add(123);
  95. setB.add(1333);
  96. console.log(setA.intersction(setB).values());