当前位置:首页 > JavaScript

js 实现集合

2026-04-06 22:52:47JavaScript

实现集合的基本方法

在 JavaScript 中,集合(Set)是一种存储唯一值的数据结构。可以使用多种方式实现集合功能。

使用 ES6 的 Set 类是最简单的方式:

const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // 重复值会被忽略
console.log(mySet.has(1)); // true
mySet.delete(1);

使用对象模拟集合

在 ES6 之前,可以用对象模拟集合:

function Set() {
  this.items = {};
}

Set.prototype.add = function(value) {
  this.items[value] = true;
};

Set.prototype.has = function(value) {
  return this.items.hasOwnProperty(value);
};

Set.prototype.delete = function(value) {
  delete this.items[value];
};

Set.prototype.size = function() {
  return Object.keys(this.items).length;
};

集合操作实现

实现集合的并集、交集和差集:

// 并集
Set.prototype.union = function(otherSet) {
  const unionSet = new Set();
  Object.keys(this.items).forEach(value => unionSet.add(value));
  Object.keys(otherSet.items).forEach(value => unionSet.add(value));
  return unionSet;
};

// 交集
Set.prototype.intersection = function(otherSet) {
  const intersectionSet = new Set();
  Object.keys(this.items).forEach(value => {
    if(otherSet.has(value)) {
      intersectionSet.add(value);
    }
  });
  return intersectionSet;
};

// 差集
Set.prototype.difference = function(otherSet) {
  const differenceSet = new Set();
  Object.keys(this.items).forEach(value => {
    if(!otherSet.has(value)) {
      differenceSet.add(value);
    }
  });
  return differenceSet;
};

使用数组实现集合

另一种实现方式是使用数组:

class ArraySet {
  constructor() {
    this.items = [];
  }

  add(value) {
    if(!this.has(value)) {
      this.items.push(value);
    }
  }

  has(value) {
    return this.items.includes(value);
  }

  delete(value) {
    const index = this.items.indexOf(value);
    if(index !== -1) {
      this.items.splice(index, 1);
    }
  }

  get size() {
    return this.items.length;
  }
}

集合的性能考虑

对于大型集合,基于对象的实现通常比数组实现性能更好,因为对象使用哈希表结构,查找操作的时间复杂度接近 O(1),而数组需要线性查找。

js 实现集合

ES6 的 Set 类已经优化了性能,建议优先使用原生 Set 而不是自定义实现,除非有特殊需求。

标签: js
分享给朋友:

相关文章

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

js钟表实现

js钟表实现

实现JavaScript钟表的基本方法 创建一个简单的JavaScript钟表可以通过以下步骤完成,涵盖数字和模拟两种形式。 数字钟表实现 HTML结构只需一个显示时间的容器: <div i…

js实现图片放大

js实现图片放大

使用 CSS transform 实现图片放大 通过 CSS 的 transform: scale() 属性实现图片放大效果。当鼠标悬停时,图片会平滑放大。 const img = document…