当前位置:首页 > 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实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

react如何使用函数

react如何使用函数

使用函数组件的基本语法 在React中,函数组件是通过JavaScript函数定义的组件。函数接收props作为参数,并返回React元素。 function Welcome(props) {…

js实现代码雨

js实现代码雨

实现代码雨效果 使用HTML5 Canvas和JavaScript可以轻松实现经典的代码雨效果。以下是完整的实现代码和说明: HTML结构 <!DOCTYPE html> <htm…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…