当前位置:首页 > JavaScript

js实现set函数

2026-02-03 08:14:26JavaScript

实现 Set 函数

在 JavaScript 中,Set 是一种内置数据结构,用于存储唯一值。如果需要手动实现类似功能,可以通过对象或数组模拟其行为。

js实现set函数

基于对象的实现

利用对象的键唯一性模拟 Set 的行为:

js实现set函数

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

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

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

CustomSet.prototype.delete = function(value) {
  if (this.has(value)) {
    delete this.items[value];
    return true;
  }
  return false;
};

CustomSet.prototype.clear = function() {
  this.items = {};
};

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

CustomSet.prototype.values = function() {
  return Object.keys(this.items);
};

基于数组的实现

通过数组存储值,并确保唯一性:

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

ArraySet.prototype.add = function(value) {
  if (!this.items.includes(value)) {
    this.items.push(value);
  }
  return this;
};

ArraySet.prototype.has = function(value) {
  return this.items.includes(value);
};

ArraySet.prototype.delete = function(value) {
  const index = this.items.indexOf(value);
  if (index !== -1) {
    this.items.splice(index, 1);
    return true;
  }
  return false;
};

ArraySet.prototype.clear = function() {
  this.items = [];
};

ArraySet.prototype.size = function() {
  return this.items.length;
};

ArraySet.prototype.values = function() {
  return [...this.items];
};

ES6 Class 实现

使用 ES6 的 class 语法实现 Set

class MySet {
  constructor() {
    this.collection = [];
  }

  has(element) {
    return this.collection.indexOf(element) !== -1;
  }

  add(element) {
    if (!this.has(element)) {
      this.collection.push(element);
      return true;
    }
    return false;
  }

  delete(element) {
    if (this.has(element)) {
      const index = this.collection.indexOf(element);
      this.collection.splice(index, 1);
      return true;
    }
    return false;
  }

  size() {
    return this.collection.length;
  }

  values() {
    return this.collection;
  }
}

注意事项

  • 对象实现的 Set 会将所有键转换为字符串,可能导致类型混淆。
  • 数组实现的 Set 在大型数据集上性能较低,因为需要遍历检查唯一性。
  • 实际开发中应优先使用原生 Set,性能更高且功能完善。

标签: 函数js
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现动画

js实现动画

使用 CSS 动画与 JavaScript 控制 通过 JavaScript 动态添加或移除 CSS 类来触发动画。CSS 定义关键帧(@keyframes),JavaScript 通过 classL…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-contain…

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Paren…

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="sli…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClip…